【发布时间】: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