在内部取消协程?

时间:2019-07-10 15:25:54

标签: kotlin coroutine

如果不满足条件,我需要在科特林退出协程。我想避免使用嵌套条件来保持代码干净。这就是我所拥有的:

GlobalScope.launch{
        var condition : Boolean  = false
        if(!condition){
            //this does nothing
            this.cancel()
        }
        println("I shouldn't print")
}

1 个答案:

答案 0 :(得分:1)

您有两种方法:

  1. 使用return@launch语句从协程体内简单返回。
  2. CancellationException一样扔this.cancel()

您的代码无法停止工作的原因是因为在协程中http://app.bmiet.net/student/attendance,您的代码应配合检查isActive或调用yield(),(就像{ {3}}表示)以实现所需的功能

相关问题