xuyanjun xuyanjun - 1 year ago 109
Android Question

Retrofit default thread

I use

in my Android app, and my code:

public void getConfig(NetworkSubscriber subscriber) {
Observable<Config> observable = mApi.getConfig();

public void getCode(String mobile, int type, NetworkSubscriber subscriber) {
Observable<BaseMessageEntity> observable = mApi.getCode(mobile, type);

And i don't want to write
every business method

How can i do?

Answer Source

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;

    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();

        public <T> Observable<?> adapt(Call<T> call) {
            return delegateAdapter.adapt(call).subscribeOn(subscribeScheduler)

and then use it instead of RxJavaCallAdapterFactory.create() in your builder --

Retrofit retrofit = new Retrofit.Builder()
    .addCallAdapterFactory(new RxThreadCallAdapter(Schedulers.io(), AndroidSchedulers.mainThread()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download