【问题标题】:Returning a value produced in Kotlin coroutine返回 Kotlin 协程中产生的值
【发布时间】:2017-11-08 21:39:55
【问题描述】:

我正在尝试返回从协程生成的值

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

我想出了以下解决方案(不是很安全!):

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

我也想过使用事件总线,但有没有更优雅的解决方案来解决这个问题?

提前致谢。

【问题讨论】:

    标签: kotlin coroutine


    【解决方案1】:

    你可以的

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

    阻塞直到结果可用。

    【讨论】:

    • @Dmytro Danylyk 我恢复了您的更改。 runBlocking 函数从未被删除,withContext 做了完全不同的事情。
    • @KirillRakhman 抱歉我看错了,以为是run。顺便说一句,我认为使用withContext 仍然更好。文档说:runBlocking 用于主要功能和测试。 kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/…
    • @DmytroDanylyk withContext 是一个 suspend 函数。有问题的代码在常规函数中。
    【解决方案2】:

    你可以用这个:

    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()
        }
    
     }
    

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2020-03-12
      • 2020-12-08
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 2019-09-24
      • 2018-02-22
      • 2019-06-18
      相关资源
      最近更新 更多