Kotlin Coroutines
Master asynchronous programming with Kotlin coroutines.
Basic Coroutine
import kotlinx.coroutines.*
fun main() {
// Launch coroutine
GlobalScope.launch {
delay(1000) // non-blocking delay
println("World!")
}
println("Hello,")
Thread.sleep(2000) // block main thread to keep JVM alive
}
Structured Concurrency
fun main() = runBlocking { // this: CoroutineScope
launch { // launch new coroutine
delay(1000L)
println("World!")
}
println("Hello,")
}
Async/Await
suspend fun fetchUser(): User {
delay(1000)
return User("Alice")
}
suspend fun fetchPosts(): List<Post> {
delay(1500)
return listOf(Post(1, "Hello"))
}
fun main() = runBlocking {
val user = async { fetchUser() }
val posts = async { fetchPosts() }
println("User: ${user.await()}, Posts: ${posts.await()}")
}
Coroutine Context
fun main() = runBlocking {
// Launch with different dispatchers
launch(Dispatchers.Default) {
// CPU-intensive work
}
launch(Dispatchers.IO) {
// I/O operations
}
launch(Dispatchers.Main) {
// UI updates (Android)
}
}
Exception Handling
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
val job = GlobalScope.launch(handler) {
throw AssertionError()
}
job.join()
}
Flow (Cold Stream)
fun simple(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
fun main() = runBlocking {
simple().collect { value -> println(value) }
}