【发布时间】:2020-12-10 17:44:44
【问题描述】:
我完全了解suspendCoroutine 和suspendCancellableCoroutine 在我的示例中是如何工作的。但我想知道为什么在我调用 viewScope.cancel() 之后执行 println("I finished") (第 13 行 - viewscope 块中的第二行)。我可以在此行之前使用 isActive 标志修复它,但我不想检查每一行。我在那里想念什么。我如何也可以取消范围?谢谢
import kotlinx.coroutines.*
import java.lang.Exception
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
fun main() {
val parentJob = Job()
val viewScope = CoroutineScope(Dispatchers.IO + parentJob)
viewScope.launch {
println(tryMe())
println("I finished")
}
Thread.sleep(2000)
viewScope.cancel()
Thread.sleep(10000)
}
suspend fun tryMe() = suspendCoroutine<String> {
println("I started working")
Thread.sleep(6000)
println("Im still working :O")
it.resume("I returned object at the end :)")
}
suspend fun tryMe2() = suspendCancellableCoroutine<String> {
println("I started working")
Thread.sleep(6000)
println("Im still working :O")
it.resume("I returned object at the end :)")
}
suspend fun tryMe3() = suspendCancellableCoroutine<String> {
it.invokeOnCancellation { println("I canceled did you heard that ?") }
println("I started working")
Thread.sleep(6000)
if (it.isActive)
println("Im still working :O")
it.resume("I returned object at the end :)")
}
【问题讨论】:
-
不要使用 Thread.sleep()。你阻塞了整个线程和其中的协程。请改用 delay()。
-
协程仅在挂起操作期间或明确告知时检查取消。
Thread.sleep没有。 -
Thread.sleep 仅用于测试目的,我无法在 suspendCancellableCoroutine 中调用延迟函数。