Roman  Elizarov
Roman Elizarov

Reputation: 28708

What is the difference between CoroutineContext and Job in kotlinx.coroutines?

In kotlinx.coroutines library all coroutine builders like launch, async, etc take CoroutineContext parameter but also have an additional parent parameter with a type of Job. What is the difference between CoroutineContext and Job?

Upvotes: 10

Views: 2477

Answers (1)

Roman  Elizarov
Roman Elizarov

Reputation: 28708

The Job represents a coroutine or some kind of an aggregate task that is being performed. A Job is a CoroutineContext.Element, which means that it can be stored in the coroutine context. The CoroutineContext is a collection of different coroutine context elements, with job being just one such element.

In fact, coroutine context is more like a map, as you can use coroutine element keys to retrieve elements from it. For example, if you have a value ctx of type CoroutineContext, then you can retrieve the job from it with ctx[Job] expression. Further details can be found in the corresponding section of coroutines design document and the documentation for CoroutineContext.

When a new coroutine is started, the full context can be specified. If this context contains a job, then the corresponding job becomes a parent for the new coroutine.

The parent parameter to coroutine builders like launch is just a convenience to make parent job specification more explicit. As documentation for launch highlights here that the explicitly specified parent job takes precedence over the job that was specified in the context. The actual example on how it can be used is given in this section of the guide.

Upvotes: 17

Related Questions