kotlin-coroutines-expert
Helps your agent use advanced patterns for Kotlin Coroutines and Flow. It understands how to handle errors and test code efficiently.
What it does
This guide teaches how to use 'Coroutines' and 'Flow' in Kotlin, which are tools for doing multiple tasks simultaneously without freezing the program. It shows how to organize these tasks, handle errors, and test your code.
When to use it
- ✓When building Kotlin programs that need to perform multiple operations concurrently.
- ✓When dealing with data streams that change over time.
- ✓When debugging issues with cancelled or failed tasks.
Example of what to ask your AI
“How can I perform two network operations at the same time in Kotlin and handle potential errors?”
Want more? Open the sections below.
How to use
The easiest way: copy the message below and paste it into Claude, ChatGPT, Cursor or any AI. It reads the skill and follows the instructions.
Skill link
Ready-to-paste message
How it works
It uses a concept called 'structured concurrency' to ensure tasks are managed properly. You also learn to use 'Flow' for handling sequential data and to manage errors in an organized way.
Installation
Easiest way: copy the skill link and paste it into Claude, ChatGPT or Cursor asking it to follow the instructions.
In the terminal (Claude Code, Codex, Cursor), in your project folder:
npx skills add sickn33/agentic-awesome-skills --skill kotlin-coroutines-expertOr download just the file:
curl -L https://raw.githubusercontent.com/sickn33/agentic-awesome-skills/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md -o SKILL.mdTechnical content (original SKILL.md)
Original text by the author, straight from GitHub.
Kotlin Coroutines Expert
Overview
A guide to mastering asynchronous programming with Kotlin Coroutines. Covers advanced topics like structured concurrency, Flow transformations, exception handling, and testing strategies.
When to Use This Skill
- Use when implementing asynchronous operations in Kotlin.
- Use when designing reactive data streams with
Flow. - Use when debugging coroutine cancellations or exceptions.
- Use when writing unit tests for suspending functions or Flows.
Step-by-Step Guide
1. Structured Concurrency
Always launch coroutines within a defined CoroutineScope. Use coroutineScope or supervisorScope to group concurrent tasks.
suspend fun loadDashboardData(): DashboardData = coroutineScope {
val userDeferred = async { userRepo.getUser() }
val settingsDeferred = async { settingsRepo.getSettings() }
DashboardData(
user = userDeferred.await(),
settings = settingsDeferred.await()
)
}
2. Exception Handling
Use CoroutineExceptionHandler for top-level scopes, but rely on try-catch within suspending functions for granular control.
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
viewModelScope.launch(handler) {
try {
riskyOperation()
} catch (e: IOException) {
// Handle network error specifically
}
}
3. Reactive Streams with Flow
Use StateFlow for state that needs to be retained, and SharedFlow for events.
// Cold Flow (Lazy)
val searchResults: Flow<List<Item>> = searchQuery
.debounce(300)
.flatMapLatest { query -> searchRepo.search(query) }
.flowOn(Dispatchers.IO)
// Hot Flow (State)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
Examples
Example 1: Parallel Execution with Error Handling
suspend fun fetchDataWithErrorHandling() = supervisorScope {
val task1 = async {
try { api.fetchA() } catch (e: CancellationException) { throw e } catch (e: IOException) { null }
}
val task2 = async { api.fetchB() }
// A child failure does not directly cancel its siblings.
// But an uncaught exception from await escapes the supervisor block and cancels it.
val result1 = task1.await()
val result2 = task2.await() // May throw
}
Best Practices
- ✅ Do: Use
Dispatchers.IOfor blocking I/O operations. - ✅ Do: Cancel scopes when they are no longer needed (e.g.,
ViewModel.onCleared). - ✅ Do: Use
TestScopeandrunTestfor unit testing coroutines. - ❌ Don't: Use
GlobalScope. It breaks structured concurrency and can lead to leaks. - ❌ Don't: Catch
CancellationExceptionunless you rethrow it.
Troubleshooting
Problem: Coroutine test hangs or fails unpredictably.
Solution: Ensure you are using runTest and injecting TestDispatcher into your classes so you can control virtual time.
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
Examples are fragments: supply imports, repository interfaces, Android lifecycle dependencies and the installed coroutines version. Handle each awaited failure deliberately and rethrow cancellation. SharedFlow replay/buffer choices determine delivery while no collector is active; it is not a guaranteed event queue. StateFlow conflates state changes. Test cancellation and slow/absent collectors, not only happy paths. Official exception behavior.
FAQ
What is 'structured concurrency'?
It's a way to organize tasks that run at the same time, ensuring they are started and stopped in a controlled manner, as if they were part of a group.
What's the difference between 'StateFlow' and 'SharedFlow'?
'StateFlow' is used to hold the current state of something (like text in a search box), while 'SharedFlow' is for sending events that might occur (like a button click).
Why shouldn't I use 'GlobalScope'?
'GlobalScope' ignores 'structured concurrency', which can cause tasks to keep running even when they shouldn't, leading to problems and memory leaks.
Details
Original description by the author
Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.
Popularity
- GitHub stars
- 48k
- Ranking position
- #3398
- License
- MIT
- Updated
- 10/15/2026
Comments
- …
More skills from this repository
00-andruia-consultant
Helps your agent start or improve AI projects. It analyzes code, suggests tools, and creates action plans in Spanish.
sickn33/agentic-awesome-skills
007
Lets your agent perform security audits and threat modeling. It's useful for protecting projects against attacks and vulnerabilities.
sickn33/agentic-awesome-skills
10-andruia-skill-smith
Helps your agent create or improve AI tools. It defines how tools work, writes documentation, and validates the structure.
sickn33/agentic-awesome-skills
20-andruia-niche-intelligence
Lets your agent create a summary about a specific industry. It's useful for understanding the context, rules, usage patterns, and risks of a project, using reliable sources.
sickn33/agentic-awesome-skills
Similar skills
benchmark-optimization-loop
Has your agent improve something's speed in a measured way. It tests multiple versions and chooses the fastest one that still works correctly.
affaan-m/ECC
change-impact
Helps your agent analyze the impact of code changes before making them. It compares the planned vs. actual results afterward, covering paths, data, tests, and documentation. Useful for risky or system-wide changes.
affaan-m/ECC
click-path-audit
Lets your agent trace all user buttons and interactions to find bugs. It finds issues where functions seem to work alone but fail together. Useful when bugs persist even after debugging.
affaan-m/ECC