我想达到什么目的?
我有一个下载图像的任务,但随着屏幕滚动,它将取消以前的下载并开始下载新的。我希望它取消 coroutine
下载以前的图像它会立即停止并释放 bandwidth
所以新图像下载速度更快。
我试过什么?
我尝试了多种方法来阻止 coroutine
但即使在取消 coroutine
后,它也会一直运行,直到完成下载。 .当我取消 coroutine
它产生一个变量isActive
至false
并停止调用进一步的挂起函数。但问题是如果它运行 loop
对于 1000000
次或从 network
下载图像除非完成,否则此任务不会取消。 Like 循环将完成它的 1000000
迭代然后协程将被取消。
我已经尝试了这些但没有成功:
job.cancel()
scope.cancel()
我已经尝试了很多方法来实现这一目标,但没有得到解决方案。我现在不能在我的项目中使用任何库。这个用例不是由 Threads、Executor Service、Coroutines 实现的。因为所有人的行为都一样。
更多类似这样的问题:
How do I cancel a kotlin coroutine for a blocking download operation
AsyncTask is not cancelling the long running operation in android
Leaking Service held by Coroutine
最佳答案
kotlin 协程必须配合才能允许取消。这意味着它有一些检查点调用一个挂起函数。这是有道理的,因为某些过程是原子的,不应该在中间停止。
一个无法取消的坏协程示例:
var job = launch {
var time = System.currentTimeMillis()
var i = 0
while (i < 1000) {
if (System.currentTimeMillis() >= time) {
println("Loop number ${++i} ")
time += 500
}
}
}
要使其可取消,您可以在每次迭代开始时添加 yield()。以下是一个可取消的协程:coroutineScope {
var job = launch {
var time = System.currentTimeMillis()
var i = 0
while (i<1000) {
yield()
if (System.currentTimeMillis() >= time) {
println("Loop number ${++i}")
time += 500
}
}
}
// wait some time
delay(1300)
println("Stopping the coroutine....")
job.cancel()
job.join()
// or call job.cancelAndJoin()
}
关于android - 如何停止或取消 Kotlin 协程(立即停止当前运行的代码块)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69097765/