改造默认线程

我在我的Android应用程序中使用RxJava进行Retrofit ,我的代码是:

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

我不想写每个业务方法.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())

我能怎么做?

Solutions Collecting From Web of "改造默认线程"

如果你不想在每次调用时指定你想要的线程,你可以创build一个RxJavaCallAdapterFactory的包装来为你的线程默认设置你的线程。

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

然后在构build器中使用它而不是RxJavaCallAdapterFactory.create()

 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(new RxThreadCallAdapter(Schedulers.io(), AndroidSchedulers.mainThread())) .build(); 

你可以使用compose()把它减less到一行。 例如,下面是您的getConfig()方法的修改版本。 它假定你正在使用retrolambda。

 public void getConfig(NetworkSubscriber subscriber) { Observable<Config> observable = mApi.getConfig(); observable .compose(this::setupThreads) .subscribe(subscriber); } 

setupThreads()方法看起来像这样:

 private <T> Observable<T> setupThreads(final Observable<T> observable) { return observable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()); } 

几个参考:

  • RxJava Wiki – 转换算子
  • Dan Lew博客文章 – 不要打破链条:使用RxJava的compose()运算符

要为subscribeOn一个默认调度程序,可以在创buildRetrofit实例时将其作为参数直接传递给RxJavaCallAdapterFactory

 new Retrofit.Builder() .client(okHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .build(); 

在Retrofit 2.0.0中介绍