首页 > 解决方案 > 即使一个或多个操作抛出异常,如何继续多个 Kotlin Coroutines 异步操作?

问题描述

假设我有以下代码:

viewModelScope.launch(Dispatchers.IO) {
  val async1 = async { throw Exception() }
  val async2 = async { throw Exception() }
  val async3 = async { throw Exception() }

  try { async1.await() } catch (e: Exception) { /* A */ }
  try { async2.await() } catch (e: Exception) { /* B */ }
  try { async3.await() } catch (e: Exception) { /* C */ }
}

我对它的期望是,即使async1抛出异常,async2async3能继续运行。

但是应用程序在调用之前崩溃了await()

我怎么能做我例外的事情?

标签: androidkotlinkotlin-coroutines

解决方案


使用supervisorScope

viewModelScope.launch(Dispatchers.IO) {
  supervisorScope {
      val async1 = async { throw Exception() }
      val async2 = async { throw Exception() }
      val async3 = async { throw Exception() }

      try { async1.await() } catch (e: Exception) { /* A */ }
      try { async2.await() } catch (e: Exception) { /* B */ }
      try { async3.await() } catch (e: Exception) { /* C */ }
  }
}

推荐阅读