使Kotlin挂起功能可取消



我想使挂起函数可取消,但isActive不可访问。这只是自动处理的吗?

suspend fun coolFunction() {
while (isActive) {
/* Do cool stuff */
}
}

要配合取消,可以定期挂起,最简单的方法是调用yield()

suspend fun coolFunction() {
while (true) {
yield()
/* Do cool stuff */
}
}

您也可以通过选中CoroutineScope.isActive来支持取消。但是suspend函数本身并不能直接访问调用它的CoroutineScope。您将不得不使用类似coroutineContext[Job]!!.isActive的东西,这很笨拙。当您直接用launch之类的东西而不是可以从任何范围调用的suspend函数来编写协程时,isActive更有用。

您可以取消正在运行挂起函数的作业或协同作用域,这样挂起函数就会取消。

private suspend fun CoroutineScope.cancelComputation() {
println("cancelComputation()")
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
// WARNING 🔥 isActive is an extension property that is available inside
// the code of coroutine via CoroutineScope object.
while (isActive) { // cancellable computation loop
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion println("main: Now I can quit.")
/*
Prints:
cancelComputation()
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
main: I'm tired of waiting!
*/
}

最新更新