Returning a value produced in Kotlin coroutine

我与影子孤独终老i 提交于 2020-08-04 05:18:19

问题


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.


回答1:


You can do

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

to block until the result is available.




回答2:


You can use this:

private val uiContext: CoroutineContext = UI
private val bgContext: CoroutineContext = CommonPool

private fun loadData() = launch(uiContext) {
 try {
  val task = async(bgContext){dataProvider.loadData("task")}
  val result = task.await() //This is the data result
  }
}catch (e: UnsupportedOperationException) {
        e.printStackTrace()
    }

 }


来源:https://stackoverflow.com/questions/44414272/returning-a-value-produced-in-kotlin-coroutine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!