Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a value produced in Kotlin coroutine

I am trying to return a value generated from coroutine

fun nonSuspending (): MyType {
    launch(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    //Do something to get the value out of coroutine context
    return somehowGetMyValue
}

I have come up with the following solution (not very safe!):

fun nonSuspending (): MyType {
    val deferred = async(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    while (deferred.isActive) Thread.sleep(1)
    return deferred.getCompleted()
}

I also thought about using event bus, but is there a more elegant solution to this problem?

Thanks in advance.

like image 812
DEDZTBH Avatar asked Jun 07 '17 13:06

DEDZTBH


1 Answers

You can do

val result = runBlocking(CommonPool) {
    suspendingFunctionThatReturnsMyValue()
}

to block until the result is available.

like image 164
Kirill Rakhman Avatar answered Nov 07 '22 00:11

Kirill Rakhman