Answer the question
In order to leave comments, you need to log in
What is the difference between calling a Coroutine?
There are 2 ways:
val unrelatedScope = MainScope()
suspend fun lostError() {
unrelatedScope.async {
throw InAsyncNoOneCanHearYou("except")
}
}
suspend fun foundError() {
coroutineScope {
async {
throw StructuredConcurrencyWill("throw")
}
}
}
async
, but I can not understand the difference.
Answer the question
In order to leave comments, you need to log in
You have already been given a direct answer in this article, read carefully:
However, there are situations where errors can get lost in coroutines.
val unrelatedScope = MainScope() // example of a lost error suspend fun lostError() { // async without structured concurrency unrelatedScope.async { throw InAsyncNoOneCanHearYou("except") } }
Note this code is declaring an unrelated coroutine scope that will launch a new coroutine without structured concurrency. Remember at the beginning I said that structured concurrency is a combination of types and programming practices, and introducing unrelated coroutine scopes in suspend functions is not following the programming practices of structured concurrency.
The error is lost in this code because async assumes that you will eventually call await where it will rethrow the exception. However, if you never do call await, the exception will be stored forever waiting patiently waiting to be raised.
Structured concurrency guarantees that when a coroutine errors, its caller or scope is notified.
If you do use structured concurrency for the above code, the error will correctly be thrown to the caller.
suspend fun foundError() { coroutineScope { async { throw StructuredConcurrencyWill("throw") } } }
In the original article in English, they write that the reason is that MainScope is called inside the suspend function and because of this, await will not be called automatically after exiting the coroutine block in the first case.
https://medium.com/androiddevelopers/coroutines-on...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question