Kotlin Coroutines Cheat Sheet

Here’s a Kotlin Coroutines cheat sheet:

Basics

Import Coroutines:

import kotlinx.coroutines.*

Launch a Coroutine:

GlobalScope.launch {
    // Coroutine code
}

Run Blocking:

runBlocking {
    // Blocking code
}

Coroutine Scope

Create a Coroutine Scope:

val coroutineScope = CoroutineScope(Dispatchers.Default)

Launch in Coroutine Scope:

coroutineScope.launch {
    // Coroutine code
}

Dispatcher

Default Dispatcher:

Dispatchers.Default // Suitable for CPU-intensive work

IO Dispatcher:

Dispatchers.IO // Suitable for IO-bound work (e.g., network, file IO)

Main Dispatcher:

Dispatchers.Main // UI thread for Android or JavaFX applications

Coroutine Context

Define Coroutine Context:

val coroutineContext = newSingleThreadContext("MyThread")

Suspend Functions

Define a Suspend Function:

suspend fun mySuspendFunction() {
    // Suspend function code
}

Async/Await

Async Coroutine:

val deferredResult: Deferred<String> = async {
    // Asynchronous code
    "Result"
}

Await Result:

val result: String = deferredResult.await()

Exception Handling

Try-Catch in Coroutine:

try {
    // Coroutine code
} catch (e: Exception) {
    // Handle exception
}

Timeout

Coroutine Timeout:

withTimeout(5000) {
    // Coroutine code
}

Supervisor Job

Supervisor Job:

val supervisorJob = SupervisorJob()

Cancel a Coroutine

Cancel Coroutine Scope:

coroutineScope.cancel()

Cancel Specific Job:

job.cancel()

Channel

Create a Channel:

val channel = Channel<Int>()

Send Data to Channel:

channel.send(42)

Receive Data from Channel:

val data = channel.receive()

Flow

Create a Flow:

fun myFlow(): Flow<Int> = flow {
    // Emit values
    emit(1)
    emit(2)
}

Collect from Flow:

myFlow().collect { value ->
    // Handle emitted value
}

This cheat sheet covers some basic and common use cases for Kotlin Coroutines. For more detailed information and advanced features, refer to the official Kotlin Coroutines documentation.