我是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协程中获取计算结果。
答案 0 :(得分:1)
launch
不返回任何内容,因此您必须:
使用async
和await
(在这种情况下,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}")
}
完全不使用启动或将启动内的代码移到挂起函数中并使用该函数的结果:
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
}