取消 Kotlin 协程任务在特定点。

huangapple go评论56阅读模式
英文:

cancel Kotlin coroutine job on certain points

问题

Kotlin协程的作业会在执行到第一个可暂停的函数时被取消。但我希望取消在我想要的特定点发生,而不是在任何可暂停的函数调用时。

我想在特定的点检查取消并手动完成作业,就像线程中断一样。
假设一个作业正在运行并达到了一个延迟函数,然后发生了取消,我想捕获取消异常并设置标志 running = false,然后继续执行作业,并在我想要的地方稍后完成作业。

考虑到当取消发生时,我希望取消延迟函数的调用,而不是等待延迟。

另外,我想提醒一下,我是在Android Studio中进行这个操作。

英文:

Kotlin coroutines jobs will be canceled when the execution reaches the first suspendable function. but I want this cancellation to happen on certain points that I want, not any suspendable function calls.

I want to check cancellation on certain points and manually finish the job, just like Thread interruptions.
Assume that a job is running and reached a delay function, then cancellation occurred, I want to catch the cancellation exception and set flag running = false, then continue executing the job and finish the job later on where I want.
Consider that I want delay function calls to be cancelled when cancellation occurs, and don't wait for the delay.
Also I want to mention that I'm doing this in android studio.

答案1

得分: 1

你尝试过使用invokeOnCompletion函数来在该任务被取消时执行所需操作吗?

大致如下:

val job = launch {
    // ...
}

job.invokeOnCompletion { 
    if (job.isCancelled) {
        // 在任务被取消时,在此处执行所需操作
        // ...
    }
}

如果需要在任务取消后继续执行任务,可以设计一些检查点来实现。

英文:

Have you tried the invokeOnCompletion function to do whatever you need when that job is cancelled?

It would be something like this:

val job = launch {

    ...

}

job.invokeOnCompletion { 
    if (job.isCancelled) {
        //Do whatever you need here when the job is cancelled
        ...
    }
}

If you need to continue with the task after its cancellation, then design it with some kind of checkpoints and then you're set.

huangapple
  • 本文由 发表于 2023年5月17日 17:57:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定