Agent Skillsmaxrave-dev/SimpMusic › kotlin-concurrency-expert

kotlin-concurrency-expert

GitHub

针对Android Kotlin代码的协程审查与修复专家。通过结构化并发、生命周期安全及最佳实践,解决ANR、内存泄漏、竞态条件等问题,确保线程安全与可测试性。

.claude/skills/kotlin-concurrency-expert/SKILL.md maxrave-dev/SimpMusic

触发场景

审查Kotlin协程并发用法 修复协程相关Bug 提升线程安全性 解决Android生命周期问题

安装

npx skills add maxrave-dev/SimpMusic --skill kotlin-concurrency-expert -g -y
更多选项

非标准路径

npx skills add https://github.com/maxrave-dev/SimpMusic/tree/dev/.claude/skills/kotlin-concurrency-expert -g -y

不安装直接使用

npx skills use maxrave-dev/SimpMusic@kotlin-concurrency-expert

指定 Agent (Claude Code)

npx skills add maxrave-dev/SimpMusic --skill kotlin-concurrency-expert -a claude-code -g -y

安装 repo 全部 skill

npx skills add maxrave-dev/SimpMusic --all -g -y

预览 repo 内 skill

npx skills add maxrave-dev/SimpMusic --list

SKILL.md

Frontmatter
{
    "name": "kotlin-concurrency-expert",
    "description": "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."
}

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

Scope Use When Lifecycle
viewModelScope ViewModel operations Cleared with ViewModel
lifecycleScope UI operations in Activity/Fragment Destroyed with lifecycle owner
repeatOnLifecycle Flow collection in UI Started/Stopped with lifecycle state
applicationScope (injected) App-wide background work Application lifetime
GlobalScope NEVER USE Breaks 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

版本历史

  • 11f5926 当前 2026-07-30 20:17

同 Skill 集合

.claude/skills/android-accessibility/SKILL.md
.claude/skills/android-architecture/SKILL.md
.claude/skills/android-coroutines/SKILL.md
.claude/skills/android-data-layer/SKILL.md
.claude/skills/android-emulator-skill/SKILL.md
.claude/skills/android-gradle-logic/SKILL.md
.claude/skills/android-retrofit/SKILL.md
.claude/skills/android-testing/SKILL.md
.claude/skills/android-viewmodel/SKILL.md
.claude/skills/coil-compose/SKILL.md
.claude/skills/compose-navigation/SKILL.md
.claude/skills/compose-performance-audit/SKILL.md
.claude/skills/compose-ui/SKILL.md
.claude/skills/gradle-build-performance/SKILL.md
.claude/skills/jetpack-compose/SKILL.md
.claude/skills/marketing-ideas/SKILL.md
.claude/skills/mobile-android-design/SKILL.md
.claude/skills/xml-to-compose-migration/SKILL.md
.claude/skills/find-skills/SKILL.md
.claude/skills/kmp/SKILL.md
.claude/skills/ui-ux-pro-max/SKILL.md

元信息

文件数
0
版本
f7205d5
Hash
7d99087c
收录时间
2026-07-30 20:17

首页 - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-01 14:25
浙ICP备14020137号-1 $访客地图$