Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxAndroid Simplify a common pattern?

I find myself writing over and over again:

Observable.create(new Observable.OnSubscribe</* some type */>() {
        @Override
        public void call(Subscriber<? super /* some type */> subscriber) {
            try {
                subscriber.onNext(/* do something */);
                subscriber.onCompleted();
            } catch (IOException e) {
                subscriber.onError(e);
            }
        }
    }).observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.newThread());

for network operations.

Is there any way to make it less repetative ?

like image 320
user47376 Avatar asked Aug 25 '26 13:08

user47376


1 Answers

The first create can be replaced by fromCallable.

Observable.fromCallable(() -> calculationReturnsAValue());

The application of schedulers can be achieved by creating a Transformer:

Transformer schedulers = o -> 
    o.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

and composing with it:

source.compose(schedulers);
like image 59
akarnokd Avatar answered Aug 28 '26 02:08

akarnokd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!