我有一个来自RxJava的Single,想继续使用Kotlin Coroutines的Deferred。如何实现这个目标?
fun convert(data: rx.Single<String>): kotlinx.coroutines.Deferred<String> = ...
我对一些库感兴趣(如果有的话?),也对自己做这件事感兴趣......到目前为止,我自己做了这个手工的实现。
private fun waitForRxJavaResult(resultSingle: Single<String>): String? {
var resultReceived = false
var result: String? = null
resultSingle.subscribe({
result = it
resultReceived = true
}, {
resultReceived = true
if (!(it is NoSuchElementException))
it.printStackTrace()
})
while (!resultReceived)
Thread.sleep(20)
return result
}
有这样一个库,将RxJava与Coroutines整合在一起。https:/github.comKotlinkotlinx.coroutinestreemasterreactivekotlinx-coroutines-rx2。
在该库中没有直接将单子转换为一个 Deferred
不过。的原因可能是RxJava的一个 Single
不绑定到coroutine作用域。如果你想把它转换为一个 Deferred
因此,你需要向它提供一个 CoroutineScope
.
你也许可以这样实现。
fun <T> Single<T>.toDeferred(scope: CoroutineScope) = scope.async { await() }
这个... Single.await
函数(用于 async
-块)来自kotlinx-coroutines-rx2库。
你可以像这样调用函数。
coroutineScope {
val mySingle = getSingle()
val deferred = mySingle.toDeferred(this)
}