Agent Skillsmaxrave-dev/SimpMusic › android-coroutines

android-coroutines

GitHub

提供Android Kotlin协程生产级规范,涵盖结构化并发、生命周期集成及响应式流。确保Dispatcher注入可测性、Main线程安全、生命周期感知收集及ViewModel状态封装,防止内存泄漏并提升代码质量。

.claude/skills/android-coroutines/SKILL.md maxrave-dev/SimpMusic

Trigger Scenarios

从API/数据库获取数据 执行后台处理任务 修复与线程或任务相关的内存泄漏 将监听器或回调转换为协程 实现ViewModel逻辑 处理UI状态更新

Install

npx skills add maxrave-dev/SimpMusic --skill android-coroutines -g -y
More Options

Non-standard path

npx skills add https://github.com/maxrave-dev/SimpMusic/tree/dev/.claude/skills/android-coroutines -g -y

Use without installing

npx skills use maxrave-dev/SimpMusic@android-coroutines

指定 Agent (Claude Code)

npx skills add maxrave-dev/SimpMusic --skill android-coroutines -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": "android-coroutines",
    "description": "Authoritative rules and patterns for production-quality Kotlin Coroutines onto Android. Covers structured concurrency, lifecycle integration, and reactive streams."
}

Android Coroutines Expert Skill

This skill provides authoritative rules and patterns for writing production-quality Kotlin Coroutines code on Android. It enforces structured concurrency, lifecycle safety, and modern best practices (2025 standards).

Responsibilities

  • Asynchronous Logic: Implementing suspend functions, Dispatcher management, and parallel execution.
  • Reactive Streams: Implementing Flow, StateFlow, SharedFlow, and callbackFlow.
  • Lifecycle Integration: Managing scopes (viewModelScope, lifecycleScope) and safe collection (repeatOnLifecycle).
  • Error Handling: Implementing CoroutineExceptionHandler, SupervisorJob, and proper try-catch hierarchies.
  • Cancellability: Ensuring long-running operations are cooperative using ensureActive().
  • Testing: Setting up TestDispatcher and runTest.

Applicability

Activate this skill when the user asks to:

  • "Fetch data from an API/Database."
  • "Perform background processing."
  • "Fix a memory leak" related to threads/tasks.
  • "Convert a listener/callback to Coroutines."
  • "Implement a ViewModel."
  • "Handle UI state updates."

Critical Rules & Constraints

1. Dispatcher Injection (Testability)

  • NEVER hardcode Dispatchers (e.g., Dispatchers.IO, Dispatchers.Default) inside classes.
  • ALWAYS inject a CoroutineDispatcher via the constructor.
  • DEFAULT to Dispatchers.IO in the constructor argument for convenience, but allow it to be overridden.
// CORRECT
class UserRepository(
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) { ... }

// INCORRECT
class UserRepository {
    fun getData() = withContext(Dispatchers.IO) { ... }
}

2. Main-Safety

  • All suspend functions defined in the Data or Domain layer must be main-safe.
  • One-shot calls should be exposed as suspend functions.
  • Data changes should be exposed as Flow.
  • The caller (ViewModel) should be able to call them from Dispatchers.Main without blocking the UI.
  • Use withContext(dispatcher) inside the repository implementation to move execution to the background.

3. Lifecycle-Aware Collection

  • NEVER collect a flow directly in lifecycleScope.launch or launchWhenStarted (deprecated/unsafe).
  • ALWAYS use repeatOnLifecycle(Lifecycle.State.STARTED) for collecting flows in Activities or Fragments.
// CORRECT
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { ... }
    }
}

4. ViewModel Scope Usage

  • Use viewModelScope for initiating coroutines in ViewModels.
  • Do not expose suspend functions from the ViewModel to the View. The ViewModel should expose StateFlow or SharedFlow that the View observes.

5. Mutable State Encapsulation

  • NEVER expose MutableStateFlow or MutableSharedFlow publicly.
  • Expose them as read-only StateFlow or Flow using .asStateFlow() or upcasting.

6. GlobalScope Prohibition

  • NEVER use GlobalScope. It breaks structured concurrency and leads to leaks.
  • If a task must survive the current scope, use an injected applicationScope (a custom scope tied to the Application lifecycle).

7. Exception Handling

  • NEVER catch CancellationException in a generic catch (e: Exception) block without rethrowing it.
  • Use runCatching only if you explicitly rethrow CancellationException.
  • Use CoroutineExceptionHandler only for top-level coroutines (inside launch). It has no effect inside async or child coroutines.

8. Cancellability

  • Coroutines feature cooperative cancellation. They don't stop immediately unless they check for cancellation.
  • ALWAYS call ensureActive() or yield() in tight loops (e.g., processing a large list, reading files) to check for cancellation.
  • Standard functions like delay() and withContext() are already cancellable.

9. Callback Conversion

  • Use callbackFlow to convert callback-based APIs to Flow.
  • ALWAYS use awaitClose at the end of the callbackFlow block to unregister listeners.

Code Patterns

Repository Pattern with Flow

class NewsRepository(
    private val remoteDataSource: NewsRemoteDataSource,
    private val externalScope: CoroutineScope, // For app-wide events
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    val newsUpdates: Flow<List<News>> = flow {
        val news = remoteDataSource.fetchLatestNews()
        emit(news)
    }.flowOn(ioDispatcher) // Upstream executes on IO
}

Parallel Execution

suspend fun loadDashboardData() = coroutineScope {
    val userDeferred = async { userRepo.getUser() }
    val feedDeferred = async { feedRepo.getFeed() }
    
    // Wait for both
    DashboardData(
        user = userDeferred.await(),
        feed = feedDeferred.await()
    )
}

Testing with runTest

@Test
fun testViewModel() = runTest {
    val testDispatcher = StandardTestDispatcher(testScheduler)
    val viewModel = MyViewModel(testDispatcher)
    
    viewModel.loadData()
    advanceUntilIdle() // Process coroutines
    
    assertEquals(expectedState, viewModel.uiState.value)
}

Version History

  • 11f5926 Current 2026-07-30 20:16

Same Skill Collection

.claude/skills/android-accessibility/SKILL.md
.claude/skills/android-architecture/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/kotlin-concurrency-expert/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

Metadata

Files
0
Version
f7205d5
Hash
05af55ae
Indexed
2026-07-30 20:16

Home - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-01 19:01
浙ICP备14020137号-1 $Map of visitor$