[JAVA] subscribeOn and observeOn

I think you may use RX Java while developing an Android application. At that time, I was addicted to the scheduler of subscribeOn and observeOn, so make a note

subscribeOn

subscribeOn specifies the thread to use for the entire RX Java stream. For example, if you have the following code (Excerpt from https://medium.com/upday-devs/rxjava-subscribeon-vs-observeon-9af518ded53a)

just("Some String") // Computation
  .map(str -> str.length()) // Computation
  .map(length -> 2 * length) // Computation
  .subscribeOn(Schedulers.computation()) // Computation
  .subscribe(number -> Log.d("", "Number " + number));// Computation

This is a Computation thread that handles the entire processing of the data flowing from the Observable.

observeOn

On the other hand, observeOn

just("Some String") // UI
  .map(str -> str.length()) // UI
  .map(length -> 2 * length) // UI
  .observeOn(Schedulers.computation()) // Computation
  .subscribe(number -> Log.d("", "Number " + number));// Computation

The process after the downstream where observeOn is placed will be the specified thread. In this code, if not specified, the UI thread processes it, but the process after specifying it in observeOn is processed by the Computation thread.

How to use properly

Consider a case where time-consuming processing such as API access is performed asynchronously, and processing that notifies the Subscriber when the data is ready is performed using RXJava. At that time, it is conceivable to specify a thread that performs asynchronous processing as a worker thread. Therefore, specify the thread that performs the entire processing with subscribeOn.

However, if you execute subscribe and operate view in it, you cannot do it in the worker thread as it is. Therefore, you can perform the view operation by observing On and processing in the UI thread when performing the view operation.

reference

http://techlife.cookpad.com/entry/2015/04/13/170000

https://medium.com/upday-devs/rxjava-subscribeon-vs-observeon-9af518ded53a

Recommended Posts

subscribeOn and observeOn