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 ?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.