如果条件不满足,我需要退出kotlin中的协程。我希望避免使用嵌套条件来保持代码的整洁。这就是我所拥有的:
GlobalScope.launch {
var condition: Boolean = false
if (!condition) {
//this does nothing
this.cancel()
}
println("I shouldn't print")
}发布于 2020-03-28 18:34:23
您有两种方法:
return@launch statement.CancellationException从您的协程主体返回,就像this.cancel()一样。您的代码不会停止工作的原因是因为在协程中,您的代码应该配合检查isActive或调用yield() (就像docs所说的那样)来实现您想要的功能
https://stackoverflow.com/questions/56973984
复制相似问题