Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Return single, execute completable after

I'm trying to accomplish the following: Return some data as single, execute a completable after. The following code does not compile due to single.andThen(). The actions need to be executed in this order.

val single = Single.create<String> { it.onSuccess("result") }
val completable = Completable.create { println("executing cleanup") }
val together = single.andThen(completable)

together.subscribe(
        { println(it) },
        { println(it) }

)
like image 200
Jeremy Avatar asked Feb 02 '18 19:02

Jeremy


3 Answers

Use flatMap:

single.flatMap(v -> completable.andThen(Single.just(v)))
like image 123
akarnokd Avatar answered Nov 03 '22 04:11

akarnokd


Note that if you don't care whether the result is Single or Completable there is a special flatMapCompletable operator in RxJava2 to execute completable after Single:

single.flatMapCompletable(result -> completable);

like image 28
Varvara Kalinina Avatar answered Nov 03 '22 06:11

Varvara Kalinina


Assuming you actually want to return the Single after the Completable, here's another way:

Using Java:

single.flatMap(x -> completable.toSingleDefault(x))

Using Kotlin:

single.flatMap { completable.toSingleDefault(it) }
like image 6
keplerian Avatar answered Nov 03 '22 06:11

keplerian