Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin协同程序从发布中获得结果_Kotlin_Coroutine_Kotlinx.coroutines - Fatal编程技术网

Kotlin协同程序从发布中获得结果

Kotlin协同程序从发布中获得结果,kotlin,coroutine,kotlinx.coroutines,Kotlin,Coroutine,Kotlinx.coroutines,我对kotlin和它的概念是新的 我在下面使用WithTimeout或Full- import kotlinx.coroutines.* fun main() = runBlocking { val result = withTimeoutOrNull(1300L) { repeat(1) { i -> println("I'm with id $i sleeping for 500 ms ..."

我对kotlin和它的概念是新的

我在下面使用WithTimeout或Full-

    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

当我不使用With Timeout或完全不使用我的第二个程序时,如何在kotlin Corroutine中获得计算结果。

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

  • 使用
    async
    await
    (在这种情况下,
    await
    会返回值)

  • 根本不使用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
    }
    

  • 我还应该注意到,在这两种情况下,您都必须在runBlocking(在try-catch中)内部处理异步或挂起函数的代码块引发的错误(因为在原始代码中,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
    }