Is there some way to achieve following:
I have 3 observables of the type Observable<MyData>
. What I want is following:
onCompleted
of the first observableonCompleted
of the second observableonCompleted
of the third observableThis can be done with concat
but then I only will be able to observe the last onCompleted
.
Ugly solution
I know, I can achieve that, if I just start the next obersvable from the onCompleted
event of the former one.
Question
Is there any other way to achieve this with even with an arbitrary number of observables? I want to avoid chaining this all together from the onCompleted
event, as this looks really ugly and the deeper the chaining goes the less clear it gets...
Edit - UseCase
I want to constantly update the UI and I want to know, when each level of data loading has finished
I hope below code helps.
Observable<MyData> observable1 = ...;
Observable<MyData> observable2 = ...;
Observable<MyData> observable3 = ...;
Observable
.concat(observable1.doOnCompleted(this::onCompleteObservable1),
observable2.doOnCompleted(this::onCompleteObservable2),
observable3.doOnCompleted(this::onCompleteObservable3))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( ... );
Here is sample methods.
void onCompleteObservable1() {
//do some work
}
void onCompleteObservable2() {
//do some work
}
void onCompleteObservable3() {
//do some work
}
I think concatMap could be the answer. With concatMap you can concatenate observables and subscribe once, so you're code could be something like:
Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.concatMap(integer -> Observable.just(integer)
.observeOn(Schedulers.computation())
.concatMap(i -> {
try {
Thread.sleep(new Random().nextInt(1000));
return Observable.just(2 * i);
} catch (InterruptedException e) {
e.printStackTrace();
return Observable.error(e);
}
}))
.subscribe(System.out::println,
Throwable::printStackTrace,
() -> System.out.println("onCompleted"));
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