使 Kotlin 挂起功能可取消

Ral*_*gha 4 kotlin

我想让挂起功能可取消,但isActive无法访问。这是自动处理的吗?

suspend fun coolFunction() {
    while (isActive) {
        /* Do cool stuff */
    }
}
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 5

为了配合取消,您可以定期暂停,最简单的方法是调用yield()

suspend fun coolFunction() {
    while (true) {
        yield()
        /* Do cool stuff */
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以通过检查支持取消CoroutineScope.isActive。但是挂起函数本身无法直接访问调用它的 CoroutineScope。你必须使用类似的东西coroutineContext[Job]!!.isActive,这很笨拙。isActive当您直接使用类似的东西launch而不是suspend可以从任何范围调用的函数来编写协程时,它更有用。