Last Updated:

What is CoroutineContext Kotlin?

What is CoroutineContext Kotlin

An article explaining what CoroutineContext is in Kotlin and what to do about it.



If you look at the definition of any corutin builder (launch, async, runBlocking, etc.) in the code, you can see that their first argument is CoroutineContext:

We also see that launch is an extension function CoroutineScope. And its last argument (actually, the code block itself) is also executed in the scope of CoroutineScope.

And now let's take a look at the definition of the most CoroutineScope:


Even Continuation, personifying corutins, also

contains CoroutineContextpublic interface Continuation {    public val context: CoroutineContext    public fun resumeWith(result: Result)}[/crayon]
In other words, CoroutineContext is the most important element of corutina. But what is it?

CoroutineContext is actually an interface for a collection of items. ElementWhere is Element - This

is JobCoroutineNameCouroutineDispatcherSupervisorJobCoroutineExceptionHandler or himself CoroutineContext.


The items in this collection have a unique key. And to retrieve elements, you can use getor square brackets:




As you can see, you can use just the name of the class as the key. In Kotlin, a class name is a reference to a companion object of that class, and in the case of CoroutineContext the companion object contains the key:



Likewise CoroutineContext can be folded, and the elements with matching keys will be replaced with new ones:


On the whole CoroutineContext is a way of transferring data between corutins. Such a transfer, for example, is carried out when starting a daughter corutina:

This code shows how the name of the corutina we specified. (main) eventually passed on to all her descendants. But if we want, we can change that name:

In fact, the rule here is simple: corutina context = parent context + descendant context.

Why do you need to know all this? For example, in order to understand what a well-known function does. withContext. It is typically used to run code on another thread, for example:

This feature simply adds the Default dispatcher to the existing CorotuneContext, thus replacing the previous disposatcher. Next, it starts a new corutina in this context, and the corutina starts working in a different thread.

Now you should understand that instead of a dispatcher in the argument of this function, you can pass any other Element, for example, the same CoroutineName. That is, with its help you can not only redirect corutins to new threads, but also change any of their characteristics.