Retrofit default thread
If you don't want to specify the threads you want on every call, you can create a wrapper around RxJavaCallAdapterFactory
to set your threads for your by default.
public class RxThreadCallAdapter extends CallAdapter.Factory {
RxJavaCallAdapterFactory rxFactory = RxJavaCallAdapterFactory.create();
private Scheduler subscribeScheduler;
private Scheduler observerScheduler;
public RxThreadCallAdapter(Scheduler subscribeScheduler, Scheduler observerScheduler) {
this.subscribeScheduler = subscribeScheduler;
this.observerScheduler = observerScheduler;
}
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
CallAdapter<Observable<?>> callAdapter = (CallAdapter<Observable<?>>) rxFactory.get(returnType, annotations, retrofit);
return callAdapter != null ? new ThreadCallAdapter(callAdapter) : null;
}
final class ThreadCallAdapter implements CallAdapter<Observable<?>> {
CallAdapter<Observable<?>> delegateAdapter;
ThreadCallAdapter(CallAdapter<Observable<?>> delegateAdapter) {
this.delegateAdapter = delegateAdapter;
}
@Override public Type responseType() {
return delegateAdapter.responseType();
}
@Override
public <T> Observable<?> adapt(Call<T> call) {
return delegateAdapter.adapt(call).subscribeOn(subscribeScheduler)
.observeOn(observerScheduler);
}
}
}
and then use it instead of RxJavaCallAdapterFactory.create()
in your builder --
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(new RxThreadCallAdapter(Schedulers.io(), AndroidSchedulers.mainThread()))
.build();
To have a default scheduler for subscribeOn
you can pass it as an argument straight to the RxJavaCallAdapterFactory
when creating your Retrofit
instance:
new Retrofit.Builder()
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build();
(For RxJava1 use RxJavaCallAdapterFactory
)
Got introduced in Retrofit 2.0.0