xuyanjun xuyanjun - 1 month ago 17
Android Question

Retrofit default thread

I use

Retrofit
with
RxJava
in my Android app, and my code:

public void getConfig(NetworkSubscriber subscriber) {
Observable<Config> observable = mApi.getConfig();
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}

public void getCode(String mobile, int type, NetworkSubscriber subscriber) {
Observable<BaseMessageEntity> observable = mApi.getCode(mobile, type);
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}


And i don't want to write
.subscribeOn(Schedulers.newThread())
and
.observeOn(AndroidSchedulers.mainThread())
every business method

How can i do?

Answer

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