MCPInstall

kotlin-concurrency-expert

Kotlin Coroutines review and remediation for Android. Use when asked to review concurrency usage, fix coroutine-related bugs, improve thread safety, or resolve lifecycle issues in Kotlin/Android code.

Installs
660
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill kotlin-concurrency-expert
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads kotlin-concurrency-expert automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Kotlin Concurrency Expert

Overview

Review and fix Kotlin Coroutines issues in Android codebases by applying structured concurrency, lifecycle safety, proper scoping, and modern best practices with minimal behavior changes.

Workflow

1. Triage the Issue

  • Capture the exact error, crash, or symptom (ANR, memory leak, race condition, incorrect state).
  • Check project coroutines setup: kotlinx-coroutines-android version, lifecycle-runtime-ktx version.
  • Identify the current scope context (viewModelScope, lifecycleScope, custom scope, or none).
  • Confirm whether the code is UI-bound (Dispatchers.Main) or intended to run off the main thread (Dispatchers.IO, Dispatchers.Default).
  • Verify Dispatcher injection patterns for testability.

2. Apply the Smallest Safe Fix

Prefer edits that preserve existing behavior while satisfying structured concurrency and lifecycle safety.

Common fixes:

  • ANR / Main thread blocking: Move heavy work to withContext(Dispatchers.IO) or Dispatchers.Default; ensure suspend functions are main-safe.
  • Memory leaks / zombie coroutines: Replace GlobalScope with a lifecycle-bound scope (viewModelScope, lifecycleScope, or injected applicationScope).
  • Lifecycle collection issues: Replace deprecated launchWhenStarted with repeatOnLifecycle(Lifecycle.State.STARTED).
  • State exposure: Encapsulate MutableStateFlow / MutableSharedFlow; expose read-only StateFlow or Flow.
  • CancellationException swallowing: Ensure generic catch (e: Exception) blocks rethrow CancellationException.
  • Non-cooperative cancellation: Add ensureActive() or yield() in tight loops for cooperative cancellation.
  • Callback APIs: Convert listeners to callbackFlow with proper awaitClose cleanup.
  • Hardcoded Dispatchers: Inject CoroutineDispatcher via constructor for testability.

Critical Rules

Dispatcher Injection (Testability)

// CORRECT: Inject dispatcher
class UserRepository(
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    suspend fun fetchUser() = withContext(ioDispatcher) { ... }
}

// INCORRECT: Hardcoded dispatcher
class UserRepository {
    suspend fun fetchUser() = withContext(Dispatchers.IO) { ... }
}

Lifecycle-Aware Collection

// CORRECT: Use repeatOnLifecycle
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { state -> updateUI(state) }
    }
}

// INCORRECT: Direct collection (unsafe, deprecated)
lifecycleScope.launchWhenStarted {
    viewModel.uiState.collect { state -> updateUI(state) }
}

State Encapsulation

// CORRECT: Expose read-only StateFlow
class MyViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(UiState())
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()
}

// INCORRECT: Exposed mutable state
class MyViewModel : ViewModel() {
    val uiState = MutableStateFlow(UiState()) // Leaks mutability
}

Exception Handling

// CORRECT: Rethrow CancellationException
try {
    doSuspendWork()
} catch (e: CancellationException) {
    throw e // Must rethrow!
} catch (e: Exception) {
    handleError(e)
}

// INCORRECT: Swallows cancellation
try {
    doSuspendWork()
} catch (e: Exception) {
    handleError(e) // CancellationException swallowed!
}

Cooperative Cancellation

// CORRECT: Check for cancellation in tight loops
suspend fun processLargeList(items: List<Item>) {
    items.forEach { item ->
        ensureActive() // Check cancellation
        processItem(item)
    }
}

// INCORRECT: Non-cooperative (ignores cancellation)
suspend fun processLargeList(items: List<Item>) {
    items.forEach { item ->
        processItem(item) // Never checks cancellation
    }
}

Callback Conversion

// CORRECT: callbackFlow with awaitClose
fun locationUpdates(): Flow<Location> = callbackFlow {
    val listener = LocationListener { location ->
        trySend(location)
    }
    locationManager.requestLocationUpdates(listener)
    
    awaitClose { locationManager.removeUpdates(listener) }
}

Scope Guidelines

ScopeUse WhenLifecycle
viewModelScopeViewModel operationsCleared with ViewModel
lifecycleScopeUI operations in Activity/FragmentDestroyed with lifecycle owner
repeatOnLifecycleFlow collection in UIStarted/Stopped with lifecycle state
applicationScope (injected)App-wide background workApplication lifetime
GlobalScopeNEVER USEBreaks structured concurrency

Testing Pattern

@Test
fun `loading data updates state`() = runTest {
    val testDispatcher = StandardTestDispatcher(testScheduler)
    val repository = FakeRepository()
    val viewModel = MyViewModel(repository, testDispatcher)
    
    viewModel.loadData()
    advanceUntilIdle()
    
    assertEquals(UiState.Success(data), viewModel.uiState.value)
}

Reference Material

FAQ

What does the kotlin-concurrency-expert skill do?

Kotlin Coroutines review and remediation for Android. Use when asked to review concurrency usage, fix coroutine-related bugs, improve thread safety, or resolve lifecycle issues in Kotlin/Android code.

How do I install kotlin-concurrency-expert?

Run npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill kotlin-concurrency-expert in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/kotlin-concurrency-expert/ (personal) or .claude/skills/kotlin-concurrency-expert/ (project).

Which AI agents can use kotlin-concurrency-expert?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is kotlin-concurrency-expert safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains kotlin-concurrency-expert?

It is published by new-silvermoon in new-silvermoon/awesome-android-agent-skills. It has 660 recorded installs.

More from new-silvermoon/awesome-android-agent-skills

View all →

android-testing

new-silvermoon/awesome-android-agent-skills

Comprehensive testing strategy involving Unit, Integration, Hilt, and Screenshot tests.

Testing & QA843 installs

gradle-build-performance

new-silvermoon/awesome-android-agent-skills

Debug and optimize Android/Gradle build performance. Use when builds are slow, investigating CI/CD performance, analyzing build scans, or identifying compilation bottlenecks.

compose-ui

new-silvermoon/awesome-android-agent-skills

Best practices for building UI with Jetpack Compose, focusing on state hoisting, detailed performance optimizations, and theming. Use this when writing or refactoring Composable functions.

Frontend & Design736 installs

android-gradle-logic

new-silvermoon/awesome-android-agent-skills

Expert guidance on setting up scalable Gradle build logic using Convention Plugins and Version Catalogs.

Mobile715 installs

android-architecture

new-silvermoon/awesome-android-agent-skills

Expert guidance on setting up and maintaining a modern Android application architecture using Clean Architecture and Hilt. Use this when asked about project structure, module setup, or dependency injection.

compose-performance-audit

new-silvermoon/awesome-android-agent-skills

Audit and improve Jetpack Compose runtime performance from code review and architecture. Use when asked to diagnose slow rendering, janky scrolling, excessive recompositions, or performance issues in Compose UI.

Popular mobile skills

View category →

design-mobile-apps

designed-by-ai/skills

Design mobile app screens with Sleek, edit Sleek projects, and implement their designs in React Native or HTML.

Mobile1.1M installs

ios-design

uizze.sh

Design and review iOS UI/UX for iPhone apps in SwiftUI, UIKit, or React Native. Use for mobile app design, screen redesigns, navigation flows, typography, forms, keyboard and safe-area layout, and accessibility checks. Apply Apple Human Interface Guidelines and consult real product references through the optional Uizze connection.

Mobile416.5K installs

vercel-react-native-skills

vercel-labs/agent-skills

React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.

OfficialMobile256.7K installs

animate-expo

emilkowalski/skills

Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use animate.

Mobile140.1K installs

xcode-project-setup

firebase/agent-skills

Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).

OfficialMobile131.2K installs

firebase-remote-config-basics

firebase/agent-skills

Manages Firebase Remote Config templates, feature flags, loading strategies, and SDKs (Android, iOS). Use when downloading/deploying remoteconfig JSON templates, managing version history/feature flags, setting in-app defaults, fetchAndActivate(), real-time listeners, or SDK setup. Don't use for Firebase Hosting, Auth, Firestore, Data Connect, Crashlytics, or App Hosting.

OfficialMobile121.7K installs