0% found this document useful (0 votes)
657 views

Kotlin Coroutines Cheat Sheet PDF

Coroutines allow writing asynchronous non-blocking code using coroutines and structured concurrency. There are different coroutine builders like launch, async, and runBlocking to start coroutines. Coroutines run on coroutine dispatchers like Default, IO, and Main that determine thread usage. Shared mutable state needs synchronization primitives like Mutex and actors to coordinate access from multiple coroutines. Actors provide a safe way to manage shared state through message passing between coroutines.

Uploaded by

geiledeutsche
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
657 views

Kotlin Coroutines Cheat Sheet PDF

Coroutines allow writing asynchronous non-blocking code using coroutines and structured concurrency. There are different coroutine builders like launch, async, and runBlocking to start coroutines. Coroutines run on coroutine dispatchers like Default, IO, and Main that determine thread usage. Shared mutable state needs synchronization primitives like Mutex and actors to coordinate access from multiple coroutines. Actors provide a safe way to manage shared state through message passing between coroutines.

Uploaded by

geiledeutsche
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

COROUTINES

CoroutineScope Coroutine dispachers


To start coroutine scope you can: Dispatchers.Default - Different thread (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
newSingleThreadContext - Creates a new coroutine
as a Job.
execution context using a single thread with built-in yield
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<V> - Atomic reference.
SupervisorJob). Mutex - Does not let more than one
CoroutineExceptionHandler - Used to set thread at the same time.
exception handling for uncaught exceptions. private val mutex = Mutex()
ContinuationInterceptor - Intercepts continuation. mutex.withLock { /**/ }
Mainly used by dispatchers.
Actors
Channels sealed class Msg
fun CoroutineScope.produceSquares(): object IncCounter: Msg()
ReceiveChannel<Int> = produce { object PrintCounter: Msg()
for (x in 1..5) send(x * x) class GetCounter(val resp: CompletableDeferred<Int>):Msg()
}
fun CoroutineScope.counterActor() = actor<Msg> {
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

You might also like