RxJava Return single, execute completable after

六眼飞鱼酱① 提交于 2020-05-11 04:40:28

问题


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

)

回答1:


Use flatMap:

single.flatMap(v -> completable.andThen(Single.just(v)))



回答2:


There is a special flatMapCompletable operator in RxJava2:

single.flatMapCompletable(result -> completable);




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/48589658/rxjava-return-single-execute-completable-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!