R
R
Rarity72020-02-15 17:48:58
Kotlin
Rarity7, 2020-02-15 17:48:58

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

What is the difference between calling coroutines?
In the article where I got this from, it is written about the loss of an error inside async, but I can not understand the difference.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Yudakov, 2020-02-15
@Rarity7

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

https://medium.com/androiddevelopers/coroutines-on...
What more explanation do you need? Here everything is very clear and with examples.

A
asd111, 2020-02-15
@asd111

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 question

Ask a Question

731 491 924 answers to any question