I am trying to understand the Square/Cash App coroutine happy path with respect to the advice to avoid heap-allocated coroutine scope references.
If I've understood the argument correctly:
1. Coroutines launched from a cancelled scope fail silently. This is bad.
2. Allocating a coroutine scope to the heap (e.g., putting it in a scoped Dagger component) increases the likelihood of this happening because it is easy for the coroutine scope to continue to be referenced even after it is cancelled.
3. Therefore, we should avoid allocating coroutine scopes to the heap.
I am assuming that this advice is mainly about lesser coroutine scopes e.g., a transaction-scoped coroutine scope or a user-scoped coroutine scope. It's not about, say, a coroutine scope with the lifecycle congruent with the entire Android app like the one in the Google samples
here:
class ArticlesRepository(
private val articlesDataSource: ArticlesDataSource,
private val externalScope: CoroutineScope, // app scoped
) {
// As we want to complete bookmarking the article even if the user moves
// away from the screen, the work is done creating a new coroutine
// from an external scope
suspend fun bookmarkArticle(article: Article) {
externalScope.launch { articlesDataSource.bookmarkArticle(article) }
.join() // Wait for the coroutine to complete
}
}
Have I got this right?
https://www.droidcon.com/2023/10/06/coroutines-flow-android-the-good-parts/