kotlin-coroutines-expert
Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.
About this skill
This skill equips an AI agent with comprehensive, expert-level understanding and guidance on asynchronous programming in Kotlin using Coroutines and Flow. It delves into advanced topics such as implementing structured concurrency, designing robust reactive data streams with Kotlin Flow (including transformations), effective exception handling mechanisms for coroutines, and strategic approaches to testing suspending functions and Flows. The agent can leverage this knowledge to answer complex questions, provide best practice recommendations, or troubleshoot common issues related to Kotlin's asynchronous programming model, effectively acting as a domain expert.
Best use case
An AI agent can use this skill to: 1. **Educate and guide developers**: Provide detailed explanations and best practices for using Kotlin Coroutines and Flow in various scenarios. 2. **Troubleshoot issues**: Help diagnose problems related to coroutine cancellations, exceptions, or inefficient Flow usage within Kotlin code. 3. **Code review and refactoring suggestions**: Offer expert advice on improving asynchronous code quality, ensuring structured concurrency, and enhancing testability. 4. **Design reactive systems**: Guide the design of data-intensive or event-driven applications using Kotlin Flow.
Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.
The AI agent will provide accurate, detailed, and expert-level advice, explanations, code examples (if applicable), or troubleshooting steps related to Kotlin Coroutines and Flow. It will demonstrate a deep understanding of concepts like structured concurrency, Flow operators, exception handling in concurrent contexts, and effective testing strategies, helping users master these advanced Kotlin features.
Practical example
Example input
Explain structured concurrency in Kotlin Coroutines and why it's important. How do I handle exceptions robustly within a Kotlin Flow pipeline? Provide examples for testing a suspending function that performs network requests. What are the best practices for transforming data with Kotlin Flow operators?
Example output
The agent, leveraging this skill, would output detailed guidance similar to: "Structured concurrency in Kotlin Coroutines ensures that all child coroutines are tracked, and their lifecycle is bound to a parent scope. This is crucial for preventing resource leaks, ensuring proper cancellation propagation, and simplifying error handling. When a parent coroutine or its scope is cancelled, all its children are automatically cancelled as well. This guarantees that your asynchronous operations are contained and managed, leading to more reliable and predictable applications. For example, using `CoroutineScope` with a `Job` allows you to tie the lifecycle of your coroutines to a UI component or a ViewModel, preventing background tasks from continuing after the component is destroyed..." (continues with detailed explanation and potentially code snippets, drawing directly from the 'guide' content provided by the skill).
When to use this skill
- - When a user asks for guidance on implementing asynchronous operations in Kotlin. - When designing reactive data streams or processing sequences of values using Kotlin Flow. - When debugging or resolving issues related to coroutine cancellations, exceptions, or deadlocks. - When needing to understand or apply best practices for structured concurrency. - When developing unit tests for Kotlin suspending functions or Flow pipelines. - When generating or reviewing Kotlin code involving asynchronous patterns.
When not to use this skill
- - When the task does not involve Kotlin, asynchronous programming, or reactive streams. - When the focus is on basic Kotlin syntax or general programming concepts unrelated to concurrency. - When direct code execution, external API calls (e.g., to a database or web service), or system interactions are required, as this skill primarily provides knowledge and guidance rather than executable actions. - When a simple 'yes/no' answer is sufficient and detailed expert advice is not needed.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/kotlin-coroutines-expert/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How kotlin-coroutines-expert Compares
| Feature / Agent | kotlin-coroutines-expert | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# 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.
```kotlin
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.
```kotlin
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.
```kotlin
// 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
```kotlin
suspend fun fetchDataWithErrorHandling() = supervisorScope {
val task1 = async {
try { api.fetchA() } catch (e: Exception) { null }
}
val task2 = async { api.fetchB() }
// If task2 fails, task1 is NOT cancelled because of supervisorScope
val result1 = task1.await()
val result2 = task2.await() // May throw
}
```
## Best Practices
- ✅ **Do:** Use `Dispatchers.IO` for blocking I/O operations.
- ✅ **Do:** Cancel scopes when they are no longer needed (e.g., `ViewModel.onCleared`).
- ✅ **Do:** Use `TestScope` and `runTest` for unit testing coroutines.
- ❌ **Don't:** Use `GlobalScope`. It breaks structured concurrency and can lead to leaks.
- ❌ **Don't:** Catch `CancellationException` unless 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.Related Skills
nestjs-expert
You are an expert in Nest.js with deep knowledge of enterprise-grade Node.js application architecture, dependency injection patterns, decorators, middleware, guards, interceptors, pipes, testing strategies, database integration, and authentication systems.
n8n-validation-expert
Expert guide for interpreting and fixing n8n validation errors.
n8n-mcp-tools-expert
Expert guide for using n8n-mcp MCP tools effectively. Use when searching for nodes, validating configurations, accessing templates, managing workflows, or using any n8n-mcp tool. Provides tool selection guidance, parameter formats, and common patterns.
mermaid-expert
Create Mermaid diagrams for flowcharts, sequences, ERDs, and architectures. Masters syntax for all diagram types and styling.
local-llm-expert
Master local LLM inference, model selection, VRAM optimization, and local deployment using Ollama, llama.cpp, vLLM, and LM Studio. Expert in quantization formats (GGUF, EXL2) and local AI privacy.
laravel-expert
Senior Laravel Engineer role for production-grade, maintainable, and idiomatic Laravel solutions. Focuses on clean architecture, security, performance, and modern standards (Laravel 10/11+).
flutter-expert
Master Flutter development with Dart 3, advanced widgets, and multi-platform deployment.
dwarf-expert
Provides expertise for analyzing DWARF debug files and understanding the DWARF debug format/standard (v3-v5). Triggers when understanding DWARF information, interacting with DWARF files, answering DWARF-related questions, or working with code that parses DWARF data.
drizzle-orm-expert
Expert in Drizzle ORM for TypeScript — schema design, relational queries, migrations, and serverless database integration. Use when building type-safe database layers with Drizzle.
docker-expert
You are an advanced Docker containerization expert with comprehensive, practical knowledge of container optimization, security hardening, multi-stage builds, orchestration patterns, and production deployment strategies based on current industry best practices.
cloudflare-workers-expert
Expert in Cloudflare Workers and the Edge Computing ecosystem. Covers Wrangler, KV, D1, Durable Objects, and R2 storage.
bevy-ecs-expert
Master Bevy's Entity Component System (ECS) in Rust, covering Systems, Queries, Resources, and parallel scheduling.