JobCancellationException StandaloneCoroutine 被取消

use*_*346 15 exception coroutine kotlin kotlin-coroutines

由于我们正在使用协程(使用 1.3.5),我们有很多崩溃:JobCancellationException - StandaloneCoroutine was cancelled

我阅读了很多关于这些问题的线程,我在生产中尝试了很多解决方案,但总是发生崩溃。

在我们所有的视图模型中,我们都使用了视图模型范围,所以没关系。

但是在我们的数据层中,我们需要启动一个跟踪事件,即触发即忘任务。在第一步中,我们使用了一个GlobalScope.launch. 我认为 CancelletationException 是由于这个全局范围,所以我删除了它并使用 aSupervisorJob和 a在数据层中创建了一个扩展CoroutineExceptionHandler

private val appScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val coroutineExceptionHandler by lazy { CoroutineExceptionHandler { _, throwable -> logw("Error occurred inside Coroutine.", throwable) } }

fun launchOnApp(block: suspend CoroutineScope.() -> Unit) {
    appScope.launch(coroutineExceptionHandler) { block() }
}
Run Code Online (Sandbox Code Playgroud)

但我总是看到这段代码崩溃。我需要使用cancelAndJoin方法吗?我可以将哪种策略与干净的建筑和这种工作一起使用?

提前致谢

Sim*_*one 13

您可以构建一个捕获取消异常的扩展实用程序,并用它执行您想要的操作:

fun CoroutineScope.safeLaunch(block: suspend CoroutineScope.() -> Unit): Job {
  return this.launch {
    try {
      block()
    } catch (ce: CancellationException) {
      // You can ignore or log this exception
    } catch (e: Exception) {
      // Here it's better to at least log the exception
      Log.e("TAG","Coroutine error", e)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以将扩展与您选择的协程范围一起使用,例如全局范围:

GlobalScope.safeLaunch{
  // here goes my suspend functions and stuff
}
Run Code Online (Sandbox Code Playgroud)

或任何视图模型范围:

myViewModel.viewModelScope.safeLaunch{
// here goes my suspend functions and stuff
}
Run Code Online (Sandbox Code Playgroud)