Reputation: 7358
I need to perform one task using one Observable, obtaining the emitted data, then using another Observable to do another query.
Normally I would use a flatmap
to chain the two Observables and just caring about the final piece of data emitted.
Now there's a need to update the view during the process. Say when the first Observable emit data, I should show a text line on the UI.
I know I can break it down to two call times, calling the 2nd Observable inside onNext()
of the first one, but that's cumbersome.
How can I achieve what I described above without going down that path? Thanks
Upvotes: 3
Views: 1228
Reputation: 4936
Here is an example from ny old project with doOnNext():
API.getVideoListObservable()
.doOnError(t -> t.printStackTrace())
.map(r -> r.getObjects())
.doOnNext(l -> VideoActivity.this.runOnUiThread(() -> fragment.updateVideoList(l)))
.doOnNext(l -> kalturaVideoList.addAll(l))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
Pay attention to the .doOnNext(l -> VideoActivity.this.runOnUiThread(() -> fragment.updateVideoList(l)))
- after it you can use flatmap()
any times, and doOnNext()
will be executed before flatmap()
Good explanation of doOnNext()
by Simon Baslé here:
doOnNext
is for side-effects: you want to react (eg. log) to item emissions in an intermediate step of your stream, for example before the stream is filtered, for transverse behavior like logging, but you still want the value to propagate down the stream.
onNext
is more final, it consumes the value.
Upvotes: 3