Switch back to original thread after executing element of a chain

85 Views Asked by At

Is it possible to achieve something like this with RxJava, and if so - how:

  1. There is chain of Rx operators, which is subscribed to with proper subscribeOn and observeOn
  2. Inside the chain, there is a need to execute something on particular scheduler (different from those mentioned above)
  3. After the above p2 is executed, chain must continue on whatever schedulers specified as part of subscription
1

There are 1 best solutions below

0
zz-m On

Yes, it's possible. Just use the observeOn() operator multiple times.

Example:

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.Schedulers;

import java.util.concurrent.TimeUnit;

public class Test3 {
    public static void main(String[] args) {
        Observable<Long> source = Observable.interval(1, TimeUnit.SECONDS);

        source.observeOn(Schedulers.io())
                .map(i -> {
                    System.out.println("Thread: " + Thread.currentThread().getName() + " map1: " + i);
                    return i;
                })
                .observeOn(Schedulers.computation())
                .map(i -> {
                    System.out.println("Thread: " + Thread.currentThread().getName() + " map2: " + i);
                    return i;
                }).subscribe();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

And the output is:

enter image description here

You can see that the two map operation happened in two different threads.