Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Schedulers for rxjava on Android

I'm using Retrofit to return rxjava Observable's for my async network calls.

I find myself repeating the following invocation:

someApiCall().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

Seems like I'm always subscribing on the IO thread and observing on the Android main thread. This seems to be the best practice that all the resources I found advocate. Perhaps other than long-running computations, I don't quite understand when we would want to deviate from this pattern.

Is there a way to remove this boilerplate by defaulting the subscribeOn and observeOn threads?

Is this a use case for rxjava plugins? (I can't find many examples of their use.)

Can I set the default threads at the network boundary by messing with the retrofit executors?

like image 231
dsg Avatar asked Jul 16 '14 19:07

dsg


People also ask

What are schedulers in RxJava?

Android Scheduler — This Scheduler is provided by rxAndroid library. This is used to bring back the execution to the main thread so that UI modification can be made. This is usually used in observeOn method.

How does RxJava work on Android?

RxJava is a Java VM implementation of ReactiveX a library for composing asynchronous and event-based programs by using observable sequences. The building blocks of RxJava are Observables and Subscribers. Observable is used for emitting items and Subscriber is used for consuming those items.

Why schedulers and how RxJava internally works with them?

RxJava Schedulers. Threading in RxJava is done with help of Schedulers. Scheduler can be thought of as a thread pool managing 1 or more threads. Whenever a Scheduler needs to execute a task, it will take a thread from its pool and run the task in that thread.

What is observeOn and subscribeOn?

The first subscribeOn changes the thread to IO thread and though the subsequent subscribeOn tries to change the thread to computation thread, it is rendered obsolete by the subscribeOn preceding it. On the contrary observeOn is able to change threads in subsequent calls as evident from the output of the logs.


1 Answers

For Observable responses, Retrofit currently sets the subscribeOn as the HTTP executor of the RestAdapter (either provided or the default). This was done to shim RxJava support into the existing behavior.

The plan for 2.0 is to provide the ability to set defaults for both subscribeOn and observeOn explicitly (whether it be both, only one, or neither).

A reason you wouldn't want always want observation on the main thread is if you needed to chain multiple API calls together, for example.

like image 193
Jake Wharton Avatar answered Oct 08 '22 01:10

Jake Wharton