返回Kotlin协程产生的值 [英] Returning a value produced in Kotlin coroutine

查看:135
本文介绍了返回Kotlin协程产生的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图返回从协程生成的值

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?

预先感谢。

推荐答案

您可以

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

阻止直到结果可用。

这篇关于返回Kotlin协程产生的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆