Kotlin Coroutines
Use when kotlin coroutines for structured concurrency including suspend functions, coroutine builders, Flow, channels, and patterns for building efficient asynchronous code with cancellation and exception handling.
What this skill does
# Kotlin Coroutines
## Introduction
Kotlin coroutines provide a powerful framework for asynchronous programming that
is lightweight, expressive, and built on structured concurrency principles.
Coroutines enable writing asynchronous code that looks and behaves like
sequential code, eliminating callback hell and improving readability.
Unlike threads, coroutines are extremely lightweight—millions can run on limited
resources. The coroutine framework includes suspend functions for non-blocking
operations, builders for launching work, Flow for reactive streams, and
comprehensive cancellation and exception handling mechanisms.
This skill covers coroutine fundamentals, builders, contexts, Flow, channels,
and production patterns for Android development and server-side Kotlin.
## Suspend Functions
Suspend functions are the building blocks of coroutines, enabling non-blocking
operations that can be paused and resumed without blocking threads.
```kotlin
// Basic suspend function
suspend fun fetchUser(id: Int): User {
delay(1000) // Suspends without blocking
return User(id, "Alice")
}
data class User(val id: Int, val name: String)
// Calling suspend functions
suspend fun loadUserProfile(id: Int): UserProfile {
val user = fetchUser(id)
val posts = fetchPosts(user.id)
return UserProfile(user, posts)
}
suspend fun fetchPosts(userId: Int): List<Post> {
delay(500)
return emptyList()
}
data class Post(val id: Int, val title: String)
data class UserProfile(val user: User, val posts: List<Post>)
// Sequential vs concurrent execution
suspend fun loadDataSequential(): Pair<User, List<Post>> {
val user = fetchUser(1)
val posts = fetchPosts(1)
return user to posts
}
suspend fun loadDataConcurrent(): Pair<User, List<Post>> = coroutineScope {
val userDeferred = async { fetchUser(1) }
val postsDeferred = async { fetchPosts(1) }
userDeferred.await() to postsDeferred.await()
}
// Suspend functions with callbacks
suspend fun fetchData(url: String): String = suspendCoroutine { continuation ->
fetchDataWithCallback(url) { result, error ->
if (error != null) {
continuation.resumeWithException(error)
} else {
continuation.resume(result)
}
}
}
fun fetchDataWithCallback(
url: String,
callback: (String, Exception?) -> Unit
) {
// Simulated callback-based API
callback("data", null)
}
// Cancellable suspend functions
suspend fun downloadFile(url: String): ByteArray =
suspendCancellableCoroutine { continuation ->
val request = startDownload(url) { data, error ->
if (error != null) {
continuation.resumeWithException(error)
} else {
continuation.resume(data)
}
}
continuation.invokeOnCancellation {
request.cancel()
}
}
class DownloadRequest {
fun cancel() {}
}
fun startDownload(url: String, callback: (ByteArray, Exception?) -> Unit):
DownloadRequest {
return DownloadRequest()
}
// Using withContext for dispatcher switching
suspend fun saveToDatabase(user: User) {
withContext(Dispatchers.IO) {
// Database operation on IO dispatcher
println("Saving user: ${user.name}")
}
}
suspend fun updateUI(user: User) {
withContext(Dispatchers.Main) {
// UI update on main thread
println("Updating UI for: ${user.name}")
}
}
```
Suspend functions are marked with the `suspend` modifier and can only be called
from other suspend functions or coroutines, ensuring proper context.
## Coroutine Builders
Coroutine builders launch coroutines with different lifecycle and result
handling semantics, enabling structured and unstructured concurrency.
```kotlin
// launch: fire-and-forget coroutine
fun launchExample() {
GlobalScope.launch {
val user = fetchUser(1)
println("User: ${user.name}")
}
}
// async: coroutine with result
fun asyncExample() {
GlobalScope.launch {
val deferredUser = async { fetchUser(1) }
val deferredPosts = async { fetchPosts(1) }
val user = deferredUser.await()
val posts = deferredPosts.await()
println("Loaded ${posts.size} posts for ${user.name}")
}
}
// runBlocking: bridges blocking and suspending worlds
fun runBlockingExample() = runBlocking {
val user = fetchUser(1)
println("User loaded: ${user.name}")
}
// coroutineScope: structured concurrency
suspend fun loadMultipleUsers(ids: List<Int>): List<User> = coroutineScope {
ids.map { id ->
async { fetchUser(id) }
}.awaitAll()
}
// supervisorScope: independent child failures
suspend fun loadDataWithSupervisor(): List<User> = supervisorScope {
val user1 = async { fetchUser(1) }
val user2 = async {
delay(100)
throw Exception("Failed")
}
// user1 succeeds even if user2 fails
listOfNotNull(
try { user1.await() } catch (e: Exception) { null }
)
}
// withTimeout: time-limited coroutines
suspend fun fetchWithTimeout(id: Int): User? {
return try {
withTimeout(2000) {
fetchUser(id)
}
} catch (e: TimeoutCancellationException) {
null
}
}
// Structured concurrency with lifecycle
class ViewModel : CoroutineScope {
private val job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
fun loadData() {
launch {
val user = fetchUser(1)
// Update UI
}
}
fun onCleared() {
job.cancel()
}
}
```
Structured concurrency with `coroutineScope` ensures child coroutines complete
before the scope exits, preventing leaks and ensuring proper cleanup.
## Coroutine Context and Dispatchers
Coroutine context defines the execution environment including dispatcher, job,
exception handler, and coroutine name for debugging.
```kotlin
// Dispatchers for thread pools
suspend fun dispatcherExamples() {
// Main: UI thread (Android/JavaFX)
withContext(Dispatchers.Main) {
println("On main thread: ${Thread.currentThread().name}")
}
// IO: for blocking I/O operations
withContext(Dispatchers.IO) {
println("On IO thread: ${Thread.currentThread().name}")
}
// Default: CPU-intensive work
withContext(Dispatchers.Default) {
println("On default thread: ${Thread.currentThread().name}")
}
// Unconfined: starts in caller thread, resumes where suspended
withContext(Dispatchers.Unconfined) {
println("Unconfined: ${Thread.currentThread().name}")
}
}
// Coroutine context elements
fun contextExample() {
val scope = CoroutineScope(
Dispatchers.Main +
SupervisorJob() +
CoroutineName("MyCoroutine") +
CoroutineExceptionHandler { _, throwable ->
println("Caught: $throwable")
}
)
scope.launch {
println("Context: $coroutineContext")
}
}
// Inheriting context
fun inheritContextExample() {
CoroutineScope(Dispatchers.Main).launch {
println("Parent: ${Thread.currentThread().name}")
launch {
// Inherits Dispatchers.Main
println("Child: ${Thread.currentThread().name}")
}
launch(Dispatchers.IO) {
// Overrides with IO dispatcher
println("Override: ${Thread.currentThread().name}")
}
}
}
// ThreadLocal context element
val threadLocalValue = ThreadLocal<String>()
suspend fun threadLocalExample() {
threadLocalValue.set("initial")
withContext(threadLocalValue.asContextElement("new value")) {
println("In context: ${threadLocalValue.get()}")
}
println("After context: ${threadLocalValue.get()}")
}
// Custom context element
data class UserId(val id: Int) : AbstractCoroutineContextElement(Key) {
companion object Key : CoroutineContext.Key<UserId>
}
suspend fun customContextExample() {
withConteRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.