我们正在将我们的项目从 RX 重构为 Kotlin 协程,但不是一次性完成的,因此我们需要我们的项目同时使用两者一段时间。
现在我们有很多像这样使用 RX single 作为返回类型的方法,因为它们是繁重、长时间运行的操作,例如 API 调用。
fun foo(): Single<String> // Heavy, long running opertation
我们希望它是这样的:
suspend fun foo(): String // The same heavy, long running opertation
当我们使用这种方法时,我们仍然希望使用 RX。
我们一直在这样做:
foo()
.subscribeOn(Schedulers.io())
.map { ... }
.subscribe { ... }
Run Code Online (Sandbox Code Playgroud)
现在我应该如何将我的挂起乐趣转换为生成一个我可以使用的 Single?
这是一个好主意吗?
Single.fromCallable {
runBlocking {
foo() // This is now a suspend fun
}
}
.subscribeOn(Schedulers.io())
.map { ... }
.subscribe { ... }
Run Code Online (Sandbox Code Playgroud)