Reputation: 4964
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
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