coroutines

为在 Android 上的生产级 Kotlin 协程使用提供权威规则与模式,涵盖结构化并发、生命周期集成以及响应式流的最佳实践与指导。

仓库最近推送
GitHub Stars
159
Forks
9
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "coroutines":https://skillpi.com/zh/skills/deepskill-8c372a44ad9b9d207f49dde809936f5487c42613d2c965a8a0819fd3d457337a。安装前核对上游来源和版本:https://github.com/hanamizuki/solopreneur。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为在 Android 上的生产级 Kotlin 协程使用提供权威规则与模式,涵盖结构化并发、生命周期集成以及响应式流的最佳实践与指导。

0 下载

介绍来源: third_party · hanamizuki · 0.0.1 参考来源

SkillPi 解读

能完成的任务
生产质量高的科特林科罗提内斯进入Android的权威性规则和模式. 包括结构化的货币、生命周期整合和反应流。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: 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)
}

版本历史

  1. solopreneur--v0.6.5 GitHub ↗
    原版更新说明

    ## 2026-11-20 — sign-offs on Codex ### solopreneur 0.6.4 → 0.6.5 `/sign-offs` now ships in the Codex package too (`codex plugin add solopreneur@solopreneur`) and runs in `codex exec`, the TUI and the Codex App. Publishing to the default local folder works inside Codex's workspace-write sandbox, which a trusted project gets in the TUI; `codex exec` starts read-only, so pass `--sandbox workspace-write`. Publishing to a static folder or the bundled server writes outside the workspace and reads the page back over the network, and so does local when its folder lies outside the workspace (from a linked worktree, pages go to the main working tree). The TUI and the App ask for your approval once per publish; `codex exec` cannot ask, so start it with that access (`--add-dir <folder>`, plus `-c sandbox_workspace_write.network_access=true` for static and server) or with `--dangerously-bypass-approvals-and-sandbox`. A blocked publish never hands out a link, and on every host the skill now tells the agent to rerun it with your permission instead of sending the page somewhere else. (#208) --- Full changelog: https://github.com/hanamizuki/solopreneur/blob/main/CHANGELOG.md

  2. solopreneur--v0.6.4 GitHub ↗
    原版更新说明

    **Removed skills:** `taste-soft`, `taste-brutalist`, `taste-minimalist`, `taste-redesign`, `taste-stitch`, `taste-output`, `taste-gpt` and `taste-image-to-code` (designer; folded into `taste-skill` upstream), and `/slide-design` (marketer). Anything that calls them by name stops resolving. ## 2026-11-20 ### solopreneur 0.6.3 → 0.6.4 New `/sign-offs` skill publishes a temporary review page for decisions that need screenshots or a ruling on several items. The reader opens one link on a phone or desktop, taps approve, revise or reject (or choices you define) on each item, adds notes, and copies a single structured reply back into the chat. Pages expire after 7 days by default, and every link is read back before it is handed out. With no setup, pages go to a local folder and open over `file://`. Configured, they go to a folder an existing web server already serves, or to a bundled server behind Tailscale Serve or any reverse proxy, on this machine or another one over SSH. On first use the skill looks at what your setup offers and proposes options. The UI is in English or Traditional Chinese. Claude Code only for now; it needs Python 3.9+ and nothing beyond the standard library. Settings go in a new `signoffs` block of `.solopreneur.json`. Where pages go (`targets` and `defaultTarget`) is read only from your user-level config, `~/.config/solopreneur/config.json` or the absolute path in `$SOLOPRENEUR_CONFIG`; a repo's own `.solopreneur.json` may set only `root`, `lang`, `ttlDays` and `replyTo`, so a cloned repo cannot send your pages anywhere. `/preview` now skips a user-level config that only configures other features. If you save sign-offs settings in `~/.config/solopreneur/config.json` without a `preview` block, update every installed copy of this plugin first: older `/preview` versions report that file as broken. When the Vercel CLI is missing, `/preview` now suggests `brew install --cask vercel`. Homebrew moved the Vercel CLI to a cask, so the old `brew install vercel-cli` hint failed. (#205, #206, #207) ### designer 0.1.11 → 0.1.12 `taste-skill` moves to tasteskill 2.5.1, and upstream folded its eight style variants into it: `taste-soft`, `taste-brutalist`, `taste-minimalist`, `taste-redesign`, `taste-stitch`, `taste-output`, `taste-gpt` and `taste-image-to-code` are removed, so anything that calls them by name stops resolving. The new `taste-skill` builds or redesigns company and product websites, as static HTML/CSS or inside an existing React, Next.js, Vue, Svelte or Astro project, from a bundled kit of photographs, UI fragments, icons and motion. A checker and a finish gate render each page in headless Chrome. The gate also runs as a Stop hook that keeps the agent working while fixable failures remain; it does nothing unless a build is in progress. It needs Node 22+ and Chrome, Edge or Chromium. `impeccable` goes from 4.1.1 to 4.10.0 and now also covers native iOS and Android screens and `DESIGN.md` design systems. Its Node scripts are replaced by a prebuilt engine binary, downloaded on first use from the upstream GitHub releases into `~/.impeccable/bin/` and checked against SHA-256 sums pinned in this plugin. Its commands are no longer pre-approved, so Claude Code may ask before running them. `init` now suggests `npx impeccable login`, which lets it save critiques to an Impeccable account; signing in is optional. The taste-skill kit makes the designer package about 41 MB. Every plugin installs from the same clone of this repo, so the marketplace download grows from about 26 MB to about 129 MB for everyone. (#206) ### marketer 0.0.12 → 0.0.13 `/slide-design` is removed. It wrapped two slide engines you had to install separately, and its AI-pattern review is what `/humanly` already does. For HTML presentations, install [frontend-slides](https://github.com/zarazhangrui/frontend-slides) or [revealjs-skill](https://github.com/ryanbbrown/revealjs-skill) directly; `/rebuild-skill-index` still adds them to the marketer index when they are installed. The `marketer` agent no longer advertises presentation design. `/humanly`'s prewrite briefs now follow their own rule against em dashes: the appendix index is a table and the dashes in the briefs are rewritten. Output did not change measurably. (#199, #205) ### ios-dev 0.4.13 → 0.4.14 The `ios-dev` agent now starts without your user, project and local `CLAUDE.md` files. Subagents don't share the main session's prompt cache, so every spawn paid for those files in full; in one measured repo the agent's starting prompt drops from about 58k to 19k tokens. When a task depends on repository conventions, the agent reads the repo's `CLAUDE.md` itself. Rules that live only in your personal `CLAUDE.md` no longer reach it, so put anything it must follow in the task prompt. Re-syncs the vendored App Store Connect skills (the upstream repo moved to `rorkai/app-store-connect-cli-skills`) and `apple-design`. New workflows cover Asset Library media (product-page headers, search creative, screenshots, previews, event artwork), compiling and packaging a prepared Swift package without an Xcode project (`asc builds compile` / `package`), an experimental read-only Apple Search plan in the ASO audit, per-territory price reads with `--resolved`, and `derive` to keep one subscription priced near a multiple of another. Also new: API-key login from a JSON file, App Store Server API reads under `asc storekit`, `asc status --until review-done`, and `--env-file` for workflows. Notarization troubleshooting now verifies the existing signature instead of removing trust overrides or re-signing the app. (#198, #204, #206) ### android-dev 0.4.13 → 0.4.14 The `android-dev` agent now starts without your user, project and local `CLAUDE.md` files, which keeps its starting prompt small for every spawn. When a task depends on repository conventions, it reads the repo's `CLAUDE.md` itself. Rules that live only in your personal `CLAUDE.md` no longer reach it, so put anything it must follow in the task prompt. The six official Android skills get their first update since August. `r8-analyzer` now ships its own analysis scripts and uses the `analyze<Variant>R8Config` Gradle task on AGP 9.3+; on older AGP it temporarily pins a newer R8 in `settings.gradle`, asking first, and reverts it afterwards. It needs Python with `protobuf` 6.33.4 or later. `agp-9-upgrade` now includes the two reference docs its steps link to (the AGP 9.0 release notes and the built-in Kotlin migration guide), which an ignore rule in this repo had left out since the skill was added. `navigation-3`, `migrate-xml-views-to-jetpack-compose`, `play-billing-library-version-upgrade` and `edge-to-edge` pick up the current upstream docs. (#204, #206) ### ai-engineer 0.3.16 → 0.3.17 Re-syncs the vendored `senior-prompt-engineer` skill. Upstream rewrote only its trigger description, so it now also activates when your prompts, chatbot or RAG answers are unreliable, or when you ask how to test them. The skill's content is unchanged. (#197) ### neo4j-dev 0.0.10 → 0.0.11 Re-syncs the vendored Neo4j skills through the 2026.10 release. `neo4j-cypher` adds Cypher 25 string interpolation, the `UUID` type and `uuid()` functions (2026.08), fulltext search through the `SEARCH` clause and map comprehensions (2026.09), and map addition (2026.10), and corrects its advice on counting days between dates. `neo4j-migration` adds upgrade notes up to the 2026 LTS: skip the 2026.07.0 and 2026.08.0 patch releases, move `high_limit` stores to the `block` format and servers to Java 25 before the LTS, use newer drivers for `UUID` values, and expect a 16-character minimum for native-user passwords. `neo4j-cli-tools` covers splitting `neo4j-admin` backups and dumps into parts. (#196) --- Full changelog: https://github.com/hanamizuki/solopreneur/blob/main/CHANGELOG.md

  3. solopreneur--v0.6.1 GitHub ↗
    原版更新说明

    ## 2026-08-16 ### solopreneur 0.6.0 → 0.6.1 `/preview` now delivers to a local Library by default: it builds a browsable catalog on your machine and returns a `file://` link instead of deploying. Vercel publishing is opt-in — ask for an online or shareable link explicitly — and one-off throwaway previews still write a single ephemeral file. The preview toolchain also works when running under Codex. (#176) Review tooling reaches Codex: `/specialist-review` runs there via a reviewer ladder that reads the specialist plugins' published knowledge skills (#190), and `/greenlight` can drive its Phase 1 review round on Codex too (#191). `/greenlight` also gains Grok CLI as an opt-in local reviewer (#186). The Codex core package grows from four skills to nine: `handoff`, `perspective`, `post-mortem`, `preview`, and `specialist-review` join `autopilot`, `greenlight`, `merge-pr`, and `plan-review` (#182). ### designer 0.1.10 → 0.1.11 Re-syncs the vendored `impeccable` skill across a large upstream cycle (4.0.3 → 4.1.1): a comp-driven design workflow ("comps are shipped screens", comp-fidelity review discipline, hero-first building), a richer decision page (full-fidelity comps, IMPECCABLE'S PICK, Safer/Bolder registers, build-path toggle), Antigravity and Hermes Agent provider support, raster-provenance auditing through the fix loop (`embed-prompt.mjs --scan`), and a batch of detector false-positive and performance fixes. (#149, #185) ### ios-dev 0.4.12 → 0.4.13 Re-syncs the `asc-*` App Store Connect skills to the current `asc` CLI. Signing setup covers App Groups provisioning, private-identity sync with file-based passwords (inline `--password` / `ASC_MATCH_PASSWORD` deprecated), an experimental device/profile reconcile workflow, and one-shot signing with an isolated temporary keychain. Xcode export documents the `release-testing` method that replaces the deprecated `ad-hoc` spelling. Release staging validates build ownership and gates metadata deletes behind `--allow-deletes`; workflows gain bounded per-step retry and timeout; localization picks up Apple's expanded locale list; Apple Ads commands are split between Platform API v1 and the deprecated v5. (#154, #189) ### android-dev 0.4.12 → 0.4.13 Removes two vendored skills that had aged into bad guidance: `gradle-logic` (pinned late-2023 AGP/Kotlin versions, contradicting the bundled `agp-9-upgrade`) and `compose-navigation` (a community Navigation 3 retelling superseded by the official `navigation-3` skill bundled here). Their upstream mappings are dropped so future syncs cannot resurrect them. (#183, #184) ### ai-engineer 0.3.15 → 0.3.16 Removes the in-house `langgraph` skill: it taught an incorrect `interrupt()` contract and an unconditional "never add a checkpointer" rule that breaks human-in-the-loop flows, with 2024-era model pins. Use the `ai-engineer` agent with current LangGraph docs instead. The plugin description now lists `ai-app-templates` as the sole in-house skill. (#183) ### neo4j-dev 0.0.9 → 0.0.10 Re-syncs the vendored Neo4j skills: `neo4j-cypher` now documents GRAPH TYPE schema DDL as GA (2026.06) — the `ALTER CURRENT GRAPH TYPE ADD/ALTER/DROP` forms, element-type syntax, and required privileges — plus the 2026.07 Cypher 25 additions (`GROUP BY` subclause, `cardinality()`, aggregates in `ORDER BY`/`WHERE`). (#153, #187) --- Full changelog: https://github.com/hanamizuki/solopreneur/blob/main/CHANGELOG.md

  4. solopreneur--v0.6.0 GitHub ↗
    原版更新说明

    ## 2026-08-12 — Codex milestone ### solopreneur 0.5.38 → 0.6.0 Promotes the Codex integration introduced in 0.5.38 to a minor release, reflecting the new officially supported platform surface. Codex users can install the verified, filtered core plugin with `autopilot`, `greenlight`, `merge-pr`, and `plan-review`. Unsupported skills remain excluded, and the documented Codex V1 limitations remain unchanged. Claude Code behavior is unchanged. There are no functional differences from 0.5.38; this version corrects the release classification and establishes Codex support as the 0.6 milestone. --- Full changelog: https://github.com/hanamizuki/solopreneur/blob/main/CHANGELOG.md

  5. solopreneur--v0.5.37 GitHub ↗
    原版更新说明

    ### solopreneur 0.5.36 → 0.5.37 `/greenlight` stops hardcoding which review bots it can see. PR-mode detection now recognizes any GitHub App that actually reviews on your repo — CodeRabbit, Cursor, Copilot, and whatever comes next qualify with zero config — while conversation-only automation (dependabot, CI notifiers) is never mistaken for a reviewer. CodeRabbit graduated from "passive, observe-only" to a triggerable reviewer like the rest. A round can now drive several reviewers at once: `select=<ids>` chooses which reviewers run, `gate=<id>` chooses the one whose clean pass ends the loop, and what a run learns about your repo's reviewers is cached per-repo in `solopreneur.json` so later rounds build on it. `/autopilot` dispatches pass the new tokens and always run unattended, so scheduled runs never stall on a reviewer prompt. (#150, #151) ### ai-engineer 0.3.13 → 0.3.14 Housekeeping: re-pinned the vendored `senior-prompt-engineer` skill to upstream's latest revision (2026-07-27). Upstream moved without changing this skill, so content is identical — the release just brings the recorded provenance current. (#131) ### neo4j-dev 0.0.7 → 0.0.8 Housekeeping: no skill or agent changes — realigns the generated Codex-surface manifest that had lagged one release behind the plugin version. --- Full changelog: https://github.com/hanamizuki/solopreneur/blob/main/CHANGELOG.md

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供生产级 Kotlin 协程在 Android 上的权威规则和模式,涵盖结构化并发、生命周期集成、响应式流等核心主题。
  • 内容详实,具有明确的实用价值,适用于 Android 开发者解决异步编程、生命周期安全、错误处理等高频痛点。
触发精准95/100

亮点

  • description 明确描述了 Skill 的核心功能,'Applicability' 章节列出了清晰的触发场景,覆盖合理,边界清晰。
结构规范98/100

亮点

  • 文档结构清晰,包含 Responsibilities、Applicability、Critical Rules & Constraints、Code Patterns 等章节,步骤划分明确,有出口条件,包含端到端示例,frontmatter 完整。
执行可靠96/100

亮点

  • 提供了正确的代码示例和最佳实践,参数使用正确,覆盖了主要异常处理,不可逆操作有明确的禁止和替代方案。
证据可验 (前四项均值)95/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。