关于rx java:如何使用Kotlin协程从延期的未来创建Observable

How to create an Observable from a Deferred future using Kotlin coroutines

我正在尝试使用带有协程的Futures创建一个Observable。

这是我尝试的方法:

1
2
3
4
5
6
7
private fun getHelloObservable(): Observable<String>{
        val deferred = GlobalScope.async {
           "Hello"
        }

        return Observable.just(deferred.await())
    }

但是出现以下错误:

Suspend function 'await' should be called only from a coroutine or
another suspend function.

有没有办法做到这一点?


您可以使用kotlinx-coroutines-rx2桥接到反应世界:

1
rxSingle { deferred.await() }

从那里就像调用toObservable()实际获得Observable一样容易。