How to convert rxJava2's Observable to Completable?
Asked Answered
G

5

34

I have Observable stream, and I want to convert it to Completable, how I could do that?

Griffie answered 3/11, 2016 at 10:40 Comment(0)
O
99

The fluent way is to use Observable.ignoreElements().

Observable.just(1, 2, 3)
.ignoreElements()

Convert it back via toObservable if needed.

Officialdom answered 3/11, 2016 at 21:4 Comment(3)
More conversions can be found here. speakerdeck.com/jakewharton/…Beecher
Note that RxJava 1 does not automatically convert this to a Completable. This functionality is achieved in v1 using Observable.toCompletable(). v1's ignoreElements() just creates another Observable without elements.Victual
flatMapCompletable can also help in this situation depending on your needsOlnee
B
18

You can do something like below.

Observable<Integer> observable = Observable.just(1, 2, 3);
Completable completable = Completable.fromObservable(observable);

Like on an Observable, you will have to subscribe to the completable to start the asynchronous process that Observable wraps.

More details can be found here in the Java doc for the method.

Beecher answered 3/11, 2016 at 14:27 Comment(0)
W
4

As I understand all this solutions will work only if Observable call onComplete, which is not enough if you want your result Completable to trigger after first onNext or onError, so for this case I'd recommend this:

Observable<Integer> observable = Observable.just(1, 2, 3);
Completable completable = observable.firstOrError().ignoreElement()
Weismannism answered 27/5, 2019 at 13:10 Comment(0)
O
0

Use Completable.merge(YourObservable()...

Ozzy answered 3/11, 2016 at 13:12 Comment(0)
C
0

You could use Completable.fromObservable(xx). That is worked fine on my project.

Coinstantaneous answered 11/12, 2018 at 7:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.