Search⌘ K
AI Features

Adding, Emptying, and Subtracting Elements and Folding Contexts

Explore how to manipulate Kotlin CoroutineContext by adding and removing elements and folding through contexts. Understand how merging contexts works and how to control coroutine behavior by managing context elements.

Adding contexts

What makes CoroutineContext truly useful is the ability to merge two of them.

The resulting context responds to both keys when we add two elements with different keys.

package kotlinx.coroutines.app

import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext

fun main() {
   val ctx1: CoroutineContext = CoroutineName("Name1")
   println(ctx1[CoroutineName]?.name) // Name1
   println(ctx1[Job]?.isActive) // null

   val ctx2: CoroutineContext = Job()
   println(ctx2[CoroutineName]?.name) // null
   println(ctx2[Job]?.isActive) // true, because "Active"
   // is the default state of a job created this way

   val ctx3 = ctx1 + ctx2
   println(ctx3[CoroutineName]?.name) // Name1
   println(ctx3[Job]?.isActive) // true
}
Adding two elements with different keys

When we add another element with the same key, like in a map, the new element replaces the ...