Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
Roman Elizarov Avatar asked Dec 07 '17 07:12

Roman Elizarov


People also ask

What is a CoroutineContext?

CoroutineContext is an interface that represents an element or a collection of elements. It is conceptually similar to a map or a set collection: it is an indexed set of Element instances like Job , CoroutineName , CouroutineDispatcher , etc. The unusual thing is that each Element is also a CoroutineContext .

What are jobs in coroutines?

Coroutines Job StatesWhen the execution of a coroutine doesn't generate Exception it ends with the completed state, instead it ends with cancelled state during exception of cancel by the user.

What is the difference between launch join and async await in Kotlin coroutines?

The difference is that launch returns a Job and does not carry any resulting value, while async returns a Deferred — a light-weight non-blocking future that represents a promise to provide a result later. You can use .

What is coroutines supervisor job?

A Supervisor Job allows you to keep a parent Job running if one of the child Jobs throws an exception. In the example above, the scope uses a SupervisorJob. I launch three coroutines on the scope. The second coroutine throws an exception.


1 Answers

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.

like image 169
Roman Elizarov Avatar answered Jan 24 '23 06:01

Roman Elizarov