【问题标题】:Kotlin coroutines get results from launchKotlin 协程从启动中获得结果
【发布时间】:2019-06-26 10:04:12
【问题描述】:

我是 kotlin 及其概念协程的新手。

我有以下协程使用 withTimeoutOrNull -

    import kotlinx.coroutines.*

    fun main() = runBlocking {

        val result = withTimeoutOrNull(1300L) {
            repeat(1) { i ->
                println("I'm with id $i sleeping for 500 ms ...")
                delay(500L)
            }
            "Done" // will get cancelled before it produces this result
        }
        println("Result is $result")
    }

输出 -

    I'm sleeping 0 ...
    Result is Done

我有另一个没有超时的协程程序 -

    import kotlinx.coroutines.*

    fun main() = runBlocking {
        val result = launch {
            repeat(1) { i ->
                println("I'm sleeping $i ...")
                delay(500L)
            }
            "Done" // will get cancelled before it produces this result
        }

        result.join()
        println("result of coroutine is ${result}")
    }

输出 -

    I'm sleeping 0 ...
    result of coroutine is StandaloneCoroutine{Completed}@61e717c2

当我不像我的第二个程序那样使用 withTimeoutOrNull 时,如何在 kotlin 协程中获得计算结果。

【问题讨论】:

    标签: kotlin coroutine kotlinx.coroutines


    【解决方案1】:

    launch 不返回任何内容,因此您必须:

    1. 使用asyncawait(在这种情况下,await 确实返回值)

      import kotlinx.coroutines.*
      
      fun main() = runBlocking {
          val asyncResult = async {
              repeat(1) { i ->
                  println("I'm sleeping $i ...")
                  delay(500L)
              }
              "Done" // will get cancelled before it produces this result
          }
      
          val result = asyncResult.await()
          println("result of coroutine is ${result}")
      }
      
    2. 根本不使用启动或将启动内的代码移动到暂停函数中并使用该函数的结果:

      import kotlinx.coroutines.*
      
      fun main() = runBlocking {
          val result = done()
          println("result of coroutine is ${result}")
      }
      
      suspend fun done(): String {
          repeat(1) { i ->
              println("I'm sleeping $i ...")
              delay(500L)
          }
          return "Done" // will get cancelled before it produces this result
      }
      

    【讨论】:

    • 我还应该注意,在这两种情况下,您都必须注意异步代码块或挂起函数在 runBlocking 中抛出的错误(在 try catch 中)(因为在原始代码中,launch 不会重新抛出错误,而是将其提供给常规错误处理程序。您可以查看here 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多