Kotlin 协程从启动中获取结果

Kotlin coroutines get results from launch

我是 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协程中获取计算结果。

launch 没有 return 任何东西,所以你必须:

  1. 使用 asyncawait(在这种情况下,await 会 return 值)

    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. 根本不使用 launch 或将 launch 中的代码移动到挂起函数中并使用该函数的结果:

    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
    }