
android-coroutines
Authoritative rules and patterns for production-quality Kotlin Coroutines onto Android. Covers structured concurrency, lifecycle integration, and reactive streams.
- Installs
- 543
- 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 android-coroutines- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads android-coroutines automatically when relevant.
- 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.
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, andcallbackFlow. - Lifecycle Integration: Managing scopes (
viewModelScope,lifecycleScope) and safe collection (repeatOnLifecycle). - Error Handling: Implementing
CoroutineExceptionHandler,SupervisorJob, and propertry-catchhierarchies. - Cancellability: Ensuring long-running operations are cooperative using
ensureActive(). - Testing: Setting up
TestDispatcherandrunTest.
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
CoroutineDispatchervia the constructor. - DEFAULT to
Dispatchers.IOin 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
suspendfunctions. - Data changes should be exposed as
Flow. - The caller (ViewModel) should be able to call them from
Dispatchers.Mainwithout 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.launchorlaunchWhenStarted(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
viewModelScopefor initiating coroutines in ViewModels. - Do not expose suspend functions from the ViewModel to the View. The ViewModel should expose
StateFloworSharedFlowthat the View observes.
5. Mutable State Encapsulation
- NEVER expose
MutableStateFloworMutableSharedFlowpublicly. - Expose them as read-only
StateFloworFlowusing.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
CancellationExceptionin a genericcatch (e: Exception)block without rethrowing it. - Use
runCatchingonly if you explicitly rethrowCancellationException. - Use
CoroutineExceptionHandleronly for top-level coroutines (insidelaunch). It has no effect insideasyncor child coroutines.
8. Cancellability
- Coroutines feature cooperative cancellation. They don't stop immediately unless they check for cancellation.
- ALWAYS call
ensureActive()oryield()in tight loops (e.g., processing a large list, reading files) to check for cancellation. - Standard functions like
delay()andwithContext()are already cancellable.
9. Callback Conversion
- Use
callbackFlowto convert callback-based APIs to Flow. - ALWAYS use
awaitCloseat the end of thecallbackFlowblock 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)
}
FAQ
What does the android-coroutines skill do?
Authoritative rules and patterns for production-quality Kotlin Coroutines onto Android. Covers structured concurrency, lifecycle integration, and reactive streams.
How do I install android-coroutines?
Run npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill android-coroutines 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/android-coroutines/ (personal) or .claude/skills/android-coroutines/ (project).
Which AI agents can use android-coroutines?
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 android-coroutines 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 android-coroutines?
It is published by new-silvermoon in new-silvermoon/awesome-android-agent-skills. It has 543 recorded installs.
More from new-silvermoon/awesome-android-agent-skills
android-testing
new-silvermoon/awesome-android-agent-skills
Comprehensive testing strategy involving Unit, Integration, Hilt, and Screenshot tests.
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.
android-gradle-logic
new-silvermoon/awesome-android-agent-skills
Expert guidance on setting up scalable Gradle build logic using Convention Plugins and Version Catalogs.
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.
kotlin-concurrency-expert
new-silvermoon/awesome-android-agent-skills
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.
Popular mobile skills
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.
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.
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.
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.
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).
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.