Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make All Observables subscribeon and observeon something

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?

like image 786
rezandro Avatar asked Jan 19 '26 02:01

rezandro


1 Answers

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.

like image 178
yosriz Avatar answered Jan 20 '26 17:01

yosriz