Augusto Carmo
Augusto Carmo

Reputation: 4964

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

Suppose I have the following code:

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

What I expected with it is that even if async1 thrown an exception, async2 and async3 continued to operate.

But the app crashes before any await() is called.

How can I do what I excepted?

Upvotes: 2

Views: 875

Answers (1)

Róbert Nagy
Róbert Nagy

Reputation: 7642

Use 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 */ }
  }
}

Upvotes: 3

Related Questions