question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Child coroutine scope

See original GitHub issue

What 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:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
fvascocommented, Oct 4, 2018

I rewrote your example using an explicit job

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 {
            try {
                println("task1 started")
                delay(100000)
            } catch (e: CancellationException) {
                println("task1 cancelled")
            }

        } // some async task
        val task2 = async { } // some async task
        awaitAll(task1, task2)
    }
}

suspend fun example() {
    val job = Job()
    withContext(job) {
        launch { refresh() }
        // await `launch` initialization or start it UNDISPATCHED
        delay(1000)
        // will cancelling this job cancel the two async tasks in `refresh()` if they have not completed yet?
        job.cancel()
    }
}

The output is

task1 started
task1 cancelled
Exception in thread "main" kotlinx.coroutines.experimental.JobCancellationException: Job was cancelled; job=JobImpl{Cancelled}@71423665

Process finished with exit code 1
1reaction
elizarovcommented, Oct 2, 2018

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 a Deferred. What is the purpose?

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found