COROUTINES CoroutineScope Coroutine dispachers To start coroutine scope you can: Dispatchers.Default - Different (if possible) Use GlobalScope that has empty coroutine context. It is backed by a shared pool of threads on JVM. Implement CoroutineScope interface. Dispatchers.Main - Platform specific main thread Create a scope from a context: (if exists). with(CoroutineScope(context = context)) ... { } Dispatchers.IO - Thread designed for offloading Coroutine builders blocking IO tasks to a shared pool of threads. Dispatchers.Unconfined - Always uses first launch - Launches new coroutine without blocking available thread (most performant dispatcher). current thread and returns a reference to the coroutine - Creates a new coroutine as a Job. newSingleThreadContext execution context using a single thread with built-in runBlocking - Runs new coroutine and blocks current support. thread interruptible until its completion. newFixedThreadPoolContext - Creates new async - Creates new coroutine and returns its future coroutine execution context with the fixed-size result as an implementation of Deferred. thread-pool and built-in yield support. withContext - Change a coroutine context for some block. Sequence builder Coroutine context val childNumbers = sequence { It is an indexed set of Element instances where every yield(1) element in this set has a unique Key. print("AAA") yieldAll(listOf(2, 3)) } EmptyCoroutineContext - Does not change childNumbers.forEach { print(it) } // 1AAA23 coroutine behavior at all. Like an empty map. CoroutineName - Sets a name of a coroutine for val nums = childNumbers.joinToString() // AAA debugging purposes. print(nums) // 1, 2, 3 Job - Lifecycle of a coroutine. Can be used to cancel coroutine. A coroutine is responsible for all children with Deal with shared state the same Job. It waits for them and cancels all of them AtomicInteger - There are atomics for primitives. if any had an error (To make children independent use AtomicReference - Atomic reference. SupervisorJob). Mutex - Does not let more than one CoroutineExceptionHandler - Used to set thread at the same time. for uncaught exceptions. private val mutex = Mutex() ContinuationInterceptor - Intercepts . mutex.withLock { /**/ } Mainly used by dispatchers. Actors Channels sealed class Msg fun CoroutineScope.produceSquares(): object IncCounter: Msg() ReceiveChannel = produce { object PrintCounter: Msg() for (x in 1..5) send(x * x) class GetCounter(val resp: CompletableDeferred):Msg() } fun CoroutineScope.counterActor() = actor { val squares = produceSquares() var counter = 0 // Actor state repeat(5) { println(squares.receive()) } // 1, 4, 9, 16, 25 for (msg in channel) { when (msg) { val squares2 = produceSquares() is IncCounter -> counter++ for(square in squares2) print(square) // 1, 4, 9, 16, 25 is PrintCounter -> print(counter) is GetCounter -> msg.resp.complete(counter) } } } Learn Kotlin with us: www.kt.academy