Kotlin协同程序从发布中获得结果
我对kotlin和它的概念是新的 我在下面使用WithTimeout或Full-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 ..."
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
会返回值)
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
}