Skip to content

CoroutineScope cancellation requires a Job #610

Closed
@ZakTaccardi

Description

@ZakTaccardi

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions