Retrofit Call Adapter for Android RxJava Threading
Posted on 27 Nov 2016 in java, rxjava, retrofit, threading by Greg E.
Retrofit RxJava Call Pattern
If you are using retrofit with RxJava observables, you are very familiar with this code:
This sets up the API call to execute on the IO thread, and run your handler to process the results on the main thread using the RxAndroid scheduler.
Well, 100% of the time you want the call to happen on the IO thread, and you almost always want the result on the main thread. The one exception here I can think of is if you want to chain calls together on a background thread, but in this case you don’t really need the observable pattern at all - just use the retrofit convention that returns Call<T>.
This is code that is repeated everywhere. It’s boilerplate, does no good and can only lead to mistakes.
Update: also see this post for a much shorter solution using Kotlin.
Removing the subscribeOn
Recognizing that you always want the call to happen on the IO thread, the RxJava2CallAdapterFactory offers an overload to set this default when you setup retrofit. Instead of calling
You can call
Pass in the IO scheduler to the adapter, and it will always be used for subscribeOn. The code in the adapter to make this happen is found here.
Removing the observeOn
The RxJava2CallAdapter does not offer a similiar method to always observe on a specific scheduler, but it can be done by creating a new adapter that wraps the existing one and modifies the observable to do this:
This adapter can also call createWithScheduler on the wrapped adapter to handle both cases.
RxThreadingCallAdapterFactory
The full class that eliminates need for both boilerplate calls is here: