我在我的Android应用中使用Retrofit
和RxJava
,以及我的代码:
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())
每种商业方法
我该怎么办?
答案 0 :(得分:17)
如果您不想在每次调用时指定所需的线程,则可以在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);
}
}
}
然后在构建器中使用它而不是RxJavaCallAdapterFactory.create()
-
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(new RxThreadCallAdapter(Schedulers.io(), AndroidSchedulers.mainThread()))
.build();
答案 1 :(得分:11)
要拥有subscribeOn
的默认计划程序,您可以在创建RxJavaCallAdapterFactory
实例时将其作为参数直接传递给Retrofit
:
new Retrofit.Builder()
.client(okHttpClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.build();
在Retrofit 2.0.0中引入
答案 2 :(得分:6)
您可以使用compose()
将其缩小到一行。例如,下面是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());
}
一些参考文献: