Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain Completable into Observable flow

Suppose you want to insert a Completable in your Observable chain, such as for each emitted element, there is a completable that runs and blocks until it completes, what option would you choose? (here the Completable.complete() is just to make an example)

  1. .flatMap { Completable.complete().andThen(Observable.just(it)) }

  2. .doOnNext { Completable.complete().blockingAwait() }

  3. something else?

like image 247
Adi B Avatar asked Nov 28 '17 14:11

Adi B


People also ask

What is difference between flowable and Observable?

Observables are used when we have relatively few items over the time and there is no risk of overflooding consumers. If there is a possibility that the consumer can be overflooded, then we use Flowable. One example could be getting a huge amount of data from a sensor. They typically push out data at a high rate.

What is difference between single and Observable?

A Single is something like an Observable, but instead of emitting a series of values — anywhere from none at all to an infinite number — it always either emits one value or an error notification.

What is flatMapCompletable?

This is what flatMapCompletable does: Maps each element of the upstream Observable into CompletableSources, subscribes to them and waits until the upstream and all CompletableSources complete.

What is RX Observable?

There are two key types to understand when working with Rx: Observable represents any object that can get data from a data source and whose state may be of interest in a way that other objects may register an interest. An observer is any object that wishes to be notified when the state of another object changes.


2 Answers

.flatMapCompletable { Completable.complete().andThen(Observable.just(it)) } // If you don't want it to return
.flatMap { Completable.complete().andThen(Observable.just(it)) } //Can be used if you want it to return Observable
like image 106
Ankit Kumar Avatar answered Sep 25 '22 08:09

Ankit Kumar


In option 2. you lose the capability of cancelling the completable because blockingAwait() is not managed by the observable flow.

If you don't need to return the emitted element, there is also flatMapCompletable.

If you need to execute the completable but also return the emitted element, then I would go with option 1.

like image 24
ESala Avatar answered Sep 26 '22 08:09

ESala