...

/

Adding, Emptying, and Subtracting Elements and Folding Contexts

Adding, Emptying, and Subtracting Elements and Folding Contexts

Learn how to add, empty, or subtract elements from a context or fold a context.

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 ...