Reputation: 79
i'm implementing http requests using retrofit and rxjava in my android app. and i have this block code repeatedly:
apiService.getFromServer()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
...
is there a way not to repeat this?
Upvotes: 3
Views: 557
Reputation: 10267
Yes, you can use the compose
operator with Transformer
object that will transform input observable to Observable
that subscribes on io, observer on mainThread (or any other transformation you like of course)
<T> Transformer<T, T> applySchedulers() {
return new Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> observable) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
and your code:
apiService.getFromServer()
.compose(applySchedulers())
...
you can read Dan Lew's great post regarding that.
Upvotes: 6