#coroutines Clear
Tags #php #kotlin #bash #go #sql #rust #typescript #html #java #python #files #utils #strings #http #concurrency #async #json #arrays #security #types #crypto #database #dates #format
Kotlin StateFlow — Observable State
`StateFlow<T>` is a hot Flow holding a single current value. Perfect for UI state in Compose/Android — always has a value, conflates intermediate values, multi-subscriber.
Kotlin async / await for Parallel Results
`async` returns a `Deferred<T>` — like a Future. Use it when you need a RESULT back, in parallel. Call `.await()` to get the value (suspends until ready).
Kotlin launch and Jobs
`launch` starts a coroutine and returns a `Job` you can join, cancel, or check status on. Fire-and-forget or join-when-ready style.
Kotlin Coroutine Timeout with withTimeout
`withTimeout(ms) { ... }` cancels the inner coroutine if it doesn't finish in time and throws `TimeoutCancellationException`. `withTimeoutOrNull` returns null instead.
Kotlin Compose LaunchedEffect — Side Effects
`LaunchedEffect(key)` runs a coroutine when the key changes. Use for one-shot init, snapshot listening, data loading, or any suspend work tied to a composition.
Kotlin withContext — Switching Dispatchers
`withContext(dispatcher)` suspends the calling coroutine, runs the block on the given dispatcher, returns the result. Use `Dispatchers.IO` for blocking I/O, `Default` for CPU work, `Main` for UI updates.
Kotlin Channel — Coroutine Communication
A `Channel<T>` is a coroutine-safe queue — producer side sends, consumer side receives. Bounded buffer applies backpressure. Use Flow when broadcasting; use Channel for hand-off between coroutines.
Kotlin Flow — Cold Async Streams
`Flow<T>` is a coroutine-based reactive stream — like Sequence but async. Cold (each collector restarts the producer) and respects cancellation. The backbone of modern Kotlin/Android reactive code.
Kotlin Coroutines — suspend Function Basics
`suspend fun` can be paused and resumed without blocking a thread. Call only from another `suspend` function or a coroutine builder (`launch`, `runBlocking`, `async`).
Kotlin Coroutine Testing with runTest
`runTest { }` from kotlinx-coroutines-test gives you a virtual time scheduler — `delay(1000)` finishes instantly while preserving ordering. No more flaky 1-second test sleeps.
Kotlin select — Choose Among Channels
`select { }` lets a coroutine wait on multiple suspending operations and proceed when the first one is ready — like nginx select() but for channels, deferreds, and timers.
Kotlin coroutineScope and Structured Concurrency
`coroutineScope { }` waits for ALL its children before returning. If any child throws, the others are cancelled. The cornerstone of structured concurrency — no leaked coroutines.
Kotlin Coroutine Cancellation
Cancellation is cooperative — your coroutine must check via `ensureActive()`, `yield()`, or any other suspending call. CPU-busy loops without a suspend point are NOT cancellable.