RxJava and parallel execution of observer code

前端 未结 5 725
一整个雨季
一整个雨季 2020-12-04 14:18

I am having the following code using RxJava Observable api :

Observable observable = fileProcessor.processFileObservable(processedFile.getAbsolut         


        
5条回答
  •  执笔经年
    2020-12-04 15:14

    Using flatMap and specify to subscribe on Schedulers.computation() will achieve concurrency.

    Here is a more practical example using Callable, from the output, we can see it will take about 2000 milliseconds to finish all the tasks.

    static class MyCallable implements Callable {
    
        private static final Object CALLABLE_COUNT_LOCK = new Object();
        private static int callableCount;
    
        @Override
        public Integer call() throws Exception {
            Thread.sleep(2000);
            synchronized (CALLABLE_COUNT_LOCK) {
                return callableCount++;
            }
        }
    
        public static int getCallableCount() {
            synchronized (CALLABLE_COUNT_LOCK) {
                return callableCount;
            }
        }
    }
    
    private static void runMyCallableConcurrentlyWithRxJava() {
        long startTimeMillis = System.currentTimeMillis();
    
        final Semaphore semaphore = new Semaphore(1);
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Observable.just(new MyCallable(), new MyCallable(), new MyCallable(), new MyCallable())
                .flatMap(new Function>() {
                    @Override
                    public ObservableSource apply(@NonNull MyCallable myCallable) throws Exception {
                        return Observable.fromCallable(myCallable).subscribeOn(Schedulers.computation());
                    }
                })
                .subscribeOn(Schedulers.computation())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
    
                    }
    
                    @Override
                    public void onNext(@NonNull Object o) {
                        System.out.println("onNext " + o);
                    }
    
                    @Override
                    public void onError(@NonNull Throwable e) {
    
                    }
    
                    @Override
                    public void onComplete() {
                        if (MyCallable.getCallableCount() >= 4) {
                            semaphore.release();
                        }
                    }
                });
    
    
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
        System.out.println("durationMillis " + (System.currentTimeMillis()-startTimeMillis));
    }
    
        

    提交回复
    热议问题