即使一个或多个操作抛出异常,如何继续多个 Kotlin Coroutines 异步操作?

How to continue multiple Kotlin Coroutines async operations even when one or more operations throw an exception?

假设我有以下代码:

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() 被调用之前崩溃。

我怎样才能做我例外的事情?

使用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 */ }
  }
}