RxJava and parallel execution of observer code

前端 未结 5 731
一整个雨季
一整个雨季 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:08

    RxJava is often misunderstood when it comes to the asynchronous/multithreaded aspects of it. The coding of multithreaded operations is simple, but understanding the abstraction is another thing.

    A common question about RxJava is how to achieve parallelization, or emitting multiple items concurrently from an Observable. Of course, this definition breaks the Observable Contract which states that onNext() must be called sequentially and never concurrently by more than one thread at a time.

    To achieve parallelism you need multiple Observables.

    This runs in a single thread:

    Observable vals = Observable.range(1,10);
    
    vals.subscribeOn(Schedulers.computation())
              .map(i -> intenseCalculation(i))
              .subscribe(val -> System.out.println("Subscriber received "
                      + val + " on "
                      + Thread.currentThread().getName()));
    

    This runs in multiple threads:

    Observable vals = Observable.range(1,10);
    
    vals.flatMap(val -> Observable.just(val)
                .subscribeOn(Schedulers.computation())
                .map(i -> intenseCalculation(i))
    ).subscribe(val -> System.out.println(val));
    

    Code and text comes from this blog post.

提交回复
热议问题