取消当前的协同例程Kotlin

时间:2020-09-03 00:49:18

标签: kotlin kotlin-coroutines

如果当前协程处于活动状态,如何取消当前协程? 这是代码

fun coRoutine2(interval: Long) {
    val coroutineScope = CoroutineScope(Dispatchers.IO)
    if (coroutineScope.isActive) {
        coroutineScope.cancel()
    } else {
        coroutineScope.launch {
            for (i in 1..progressBar.max) {
                delay(interval)
                progressBar.progress = i
                println(i)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果要取消协程,则应取消调用Job方法时返回的launch对象

val job = coroutineScope.launch {
            for (i in 1..progressBar.max) {
                delay(interval)
                progressBar.progress = i
                println(i)
            }
        }
job.cancel()

official documentation

中查看更多示例