CoroutineScope cancellation requires a Job
See original GitHub issueI expected a CoroutineScope
to be cancellable on it’s own. But a Job
must be specified for a CoroutineScope
to be cancelled. This seems a bit odd and error-prone.
Example
The following fails with IllegalStateException: Scope should no longer be active
:
val scope = CoroutineScope(dispatcher)
check(scope.isActive) { "Scope should be active" }
scope.coroutineContext.cancel()
check(!scope.coroutineContext.isActive) { "Dispatcher should no longer be active" }
check(!scope.isActive) { "Scope should no longer be active" } // fails here
But if you cancel via a job, no problems:
val job = Job()
val scope = CoroutineScope(dispatcher + job)
check(scope.isActive) { "Scope should be active" }
job.cancel()
check(!scope.coroutineContext.isActive) { "Dispatcher should no longer be active" }
check(!scope.isActive) { "Scope should no longer be active" }
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:5 (5 by maintainers)
Top Results From Across the Web
Cancellation in coroutines - Medium
The coroutine work doesn't just stop when cancel is called. Rather, we need to modify our code and check if the coroutine is...
Read more >Cancellation in Kotlin Coroutines - Kt. Academy
The coroutine can run as long as it needs to clean up all the resources. However, suspension is no longer allowed. The Job...
Read more >CoroutineScope & job.cancel() issue - Kotlin Discussions
Cancels all children jobs of this coroutine using Job.cancel for all of them. Unlike Job.cancel on this job as a whole, the state...
Read more >Jobs, Waiting, Cancellation in Kotlin Coroutines
A Job is a cancellable thing with a life-cycle that culminates in its completion.Coroutine job is created with launch coroutine builder. It runs ......
Read more >After a coroutine scope is canceled, can it still be used again?
See the CoroutineScope() function implementation and notice a Job is added if none found in the context. When you call cancel() on the ......
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
Nope. That was bad idea. We’ll create
Job()
if it is missing. This way, we’ll need no change to.isActive
documentation eitherShould the documentation fixed?
isActive
andcoroutineContext.isActive
have different behaviour, despite the documentation.