Search code examples
kotlinrx-javaobservablekotlinx.coroutines

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


I'm trying to create an Observable using Futures with Coroutines.

Here is what I tried:

private fun getHelloObservable(): Observable<String>{
        val deferred = GlobalScope.async {
            "Hello"
        }

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

But I get the following error:

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

Is there a way to do this?


Solution

  • You could use kotlinx-coroutines-rx2 to bridge to the reactive world:

    rxSingle { deferred.await() }
    

    And from there it's as easy as calling toObservable() to actually get an Observable.