How to make flatMap execute on background thread How to make flatMap execute on background thread multithreading multithreading

How to make flatMap execute on background thread



I just add observeOn(Schedulers.newThread()) before flatMap and it works!


This moves just one step in the pipeline to the background thread:

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

Originally answered here:https://stackoverflow.com/a/35429084/2908525


There is a good chance when you create the MyLoader object in the main thread the Observable.create be executed as well (or maybe somewhere else before in your code (?) ). If it's so, the .subscribeOn(Schedulers.io()) will have no effect on changing the thread.

You can try wrap the .create() with a .defer() to make sure the Observable is created only when it's subscribed.

e.g. defer(() -> create(....))