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

2.5k views Asked by At

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?

1

There are 1 answers

1
tynn On BEST ANSWER

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.