Raj*_*jan 5 coroutine kotlin kotlinx.coroutines
我是 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")
}
Run Code Online (Sandbox Code Playgroud)
输出 -
I'm sleeping 0 ...
Result is Done
Run Code Online (Sandbox Code Playgroud)
我有另一个没有超时的协程程序 -
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}")
}
Run Code Online (Sandbox Code Playgroud)
输出 -
I'm sleeping 0 ...
result of coroutine is StandaloneCoroutine{Completed}@61e717c2
Run Code Online (Sandbox Code Playgroud)
当我不像我的第二个程序那样使用 withTimeoutOrNull 时,如何在 kotlin 协程中获得计算结果。
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}")
}
Run Code Online (Sandbox Code Playgroud)根本不使用启动或将启动内的代码移动到挂起函数中并使用该函数的结果:
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
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
2894 次 |
| 最近记录: |