Kotlin Coroutines

Asynchronous programming with coroutines

Launch Coroutine

import kotlinx.coroutines.*
runBlocking { # blocking coroutine scope
    launch { # launch coroutine
        delay(1000L) # non-blocking delay
        println("World")
    }
    println("Hello")
}

Async and Await

val deferred = async { # async returns Deferred
    delay(1000L)
    "Result"
}
val result = deferred.await() # wait for result

Coroutine Scope

GlobalScope.launch { # global scope
    delay(1000L)
}
coroutineScope { # suspending function scope
    launch { }
}

Suspend Functions

suspend fun fetchData(): String { # suspending function
    delay(1000L) # can call suspend functions
    return "Data"
}

Dispatchers

launch(Dispatchers.Main) { } # UI thread
launch(Dispatchers.IO) { } # IO operations
launch(Dispatchers.Default) { } # CPU-intensive work