android - 如何停止或取消 Kotlin 协程(立即停止当前运行的代码块)?

标签 android kotlin kotlin-coroutines coroutine coroutinescope

我想达到什么目的?
我有一个下载图像的任务,但随着屏幕滚动,它将取消以前的下载并开始下载新的。我希望它取消 coroutine下载以前的图像它会立即停止并释放 bandwidth所以新图像下载速度更快。
我试过什么?
我尝试了多种方法来阻止 coroutine但即使在取消 coroutine 后,它也会一直运行,直到完成下载。 .当我取消 coroutine它产生一个变量isActivefalse并停止调用进一步的挂起函数。但问题是如果它运行 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/

相关文章:

android - 如何在 Android/iOS 移动 SDK 产品中捕获日志和崩溃报告?

android - Android资源编译失败-AAPT错误-资源重复值

java - JAXB 将 xml 列表元素解码为单个 Kotlin 对象

performance - Kotlin:大量 ConsPStack,我该如何避免?

kotlin - Kotlin协程:暂停后续访问 token 续订请求

kotlin - 取消信号上的Kotlin流收集

android - 如何在工具栏中添加图像

java.net.BindException : EADDRINUSE (Address already in use)

android - 如何获取标签android的位置?

android - Kotlin流程: callbackFlow with lazy initializer of callback object