RxJava Return single, execute completable after
Asked Answered
L

4

18

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) }

)
Loot answered 2/2, 2018 at 19:31 Comment(0)
A
43

Use flatMap:

single.flatMap(v -> completable.andThen(Single.just(v)))
Al answered 2/2, 2018 at 19:37 Comment(0)
R
6

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) }
Relative answered 29/8, 2019 at 0:45 Comment(0)
S
5

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);

Stalder answered 16/8, 2019 at 12:35 Comment(5)
Simple and elegant tnxErnaldus
This returns a Completable. The initial question wants it to return a Single.Disaffection
@DouglasKazumi will this work? val together = single.flatMap { result -> completable.andThen(Single.just(result)) }Stalder
@VarvaraKalinina yes! That's exactly what the accepted answer proposes. I like this syntax better.Disaffection
@DouglasKazumi Ok, you are right :) My answer is incorrect when you do care about the return type (Single). Edited my answerStalder
V
0

If anyone is interested in a the RxSwift solution:

saveObjectsA().flatMap { (objectsA: [A]) -> Single<Bool> in
        B.objects = objectsA
        return completable.andThen(Single.just(true))
    }

saveObjectsA returns a Single<[A]> which is an attribute of B (created previously). I needed to save it before saving B.

Voidable answered 9/1, 2019 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.