Child coroutine scope
See original GitHub issueWhat is the recommended pattern from within a suspend function to launch a new child coroutine from the current scope?
I want to ensure that cancelling the parent scope cancels any coroutines launched by the child scopes.
Is the below the best practice for achieving this?
suspend fun refresh() {
// need to build a new coroutine scope that is the child of the current coroutine scope (from `suspend`)
coroutineScope { // <-- child scope
val task1 = async { } // some async task
val task2 = async { } // some async task
awaitAll(task1, task2)
}
}
suspend fun example(scope: CoroutineScope) {
scope.launch { refresh() }
// will cancelling this job cancel the two async tasks in `refresh()` if they have not completed yet?
scope.coroutineContext[Job]!!.cancel()
}
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Create a child coroutine scope in Kotlin - Stack Overflow
It is a child of a current coroutine for structured concurrency, · It can be stored in some property, etc. and later be...
Read more >Job and children awaiting in Kotlin Coroutines - Kt. Academy
When a coroutine is executing its body, it is surely in the "Active" state. When it is done, its state changes to "Completing",...
Read more >Kotlin Coroutine Scope, Context, and Job made simple | by Elye
Jobs can be hierarchical (parent-child relationship) If a launch is triggered in another coroutine (under the same scope context), the job of ...
Read more >children - Kotlin
A job becomes a child of this job when it is constructed with this job in its CoroutineContext or using an explicit parent...
Read more >Cancelling child coroutines - Lanky Dan Blog
Cancelling a job cancels its children. Cancelling a parent coroutine/job will also cancel all of its child coroutines. Allowing you to submit a ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I rewrote your example using an explicit job
The output is
What you are trying to achieve here? Can you, please, give little bit more details about your problem and the context of what you are trying to do. Why do you have
suspend fun
that is also returning aDeferred
. What is the purpose?