@Rarity7

В чем отличие между вызовом Корутин?

Есть 2 способа:
val unrelatedScope = MainScope()
suspend fun lostError() {
    unrelatedScope.async {
        throw InAsyncNoOneCanHearYou("except")
    }
}


suspend fun foundError() {
    coroutineScope {
        async { 
            throw StructuredConcurrencyWill("throw")
        }
    }
}

В чем отличие между вызовом корутин?
В статье, откуда я это взял написано о потере ошибки внутри async, но не могу понять разницу.
  • Вопрос задан
  • 467 просмотров
Решения вопроса 1
AlexanderYudakov
@AlexanderYudakov
C#, 1С, Android, TypeScript
Вам уже дали прямой ответ в этой статье, читайте внимательнее:


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")
        }
    }
}

https://medium.com/androiddevelopers/coroutines-on...

Какое еще объяснение вам нужно? Здесь все предельно понятно и с примерами.
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@asd111
В оригинальной статье на англ пишут что причина в том что вызывается MainScope внутри suspend ф-ции и из за этого не будет вызван await автоматически после выхода из блока корутины в первом случае.
https://medium.com/androiddevelopers/coroutines-on...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы