如果当前协程处于活动状态,如何取消当前协程? 这是代码
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)
}
}
}
}
答案 0 :(得分:1)
如果要取消协程,则应取消调用Job
方法时返回的launch
对象
val job = coroutineScope.launch {
for (i in 1..progressBar.max) {
delay(interval)
progressBar.progress = i
println(i)
}
}
job.cancel()
中查看更多示例