Reputation: 6432
I have an Observable
on which I'm applying the flatMap
operator. Is it possible to make this original Observable
complete when the second one completes?
Here is the code.
Observable.never<Int>()
.startWith(0)
.doOnComplete { println("Completed") } // Not called.
.flatMap { Observable.fromArray(1, 2, 3, 4, 5) /* Completes after 5 */ }
.subscribe(::println)
The output is:
1
2
3
4
5
I'm trying to achieve the following output:
1
2
3
4
5
Completed
Upvotes: 2
Views: 55
Reputation: 3253
You can make use of operator materialize
which will help you get information about what is hapening inside flatMap
. Then you can dispose upstream when you receive onComplete
notification(by taking only onNext
Notifications).
Observable.<Integer>never()
.startWith(0)
.flatMap(integer -> Observable.range(1, 5)
.materialize())
.takeWhile(notification -> notification.isOnNext())
.map(notification -> notification.getValue())
.doOnComplete(() -> System.out.println("Completed"))
.subscribe(integer -> System.out.println(integer));
Result
1
2
3
4
5
Completed
Upvotes: 1