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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With