[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-4990589c-27a8-41f9-9d96-63af0b892165":3,"$fYg2f6YgL0wjvY6n_J0fjMO8REHgJSTrKRiHMq6azHGw":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"4990589c-27a8-41f9-9d96-63af0b892165","kotlin-coroutines-expert","Kotlin协程和Flow的专家模式，涵盖结构化并发、错误处理和测试。","cat_coding_frontend","mod_coding","sickn33,coding","---\nname: kotlin-coroutines-expert\ndescription: \"Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.\"\nrisk: safe\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Kotlin Coroutines Expert\n\n## Overview\n\nA guide to mastering asynchronous programming with Kotlin Coroutines. Covers advanced topics like structured concurrency, `Flow` transformations, exception handling, and testing strategies.\n\n## When to Use This Skill\n\n- Use when implementing asynchronous operations in Kotlin.\n- Use when designing reactive data streams with `Flow`.\n- Use when debugging coroutine cancellations or exceptions.\n- Use when writing unit tests for suspending functions or Flows.\n\n## Step-by-Step Guide\n\n### 1. Structured Concurrency\n\nAlways launch coroutines within a defined `CoroutineScope`. Use `coroutineScope` or `supervisorScope` to group concurrent tasks.\n\n```kotlin\nsuspend fun loadDashboardData(): DashboardData = coroutineScope {\n    val userDeferred = async { userRepo.getUser() }\n    val settingsDeferred = async { settingsRepo.getSettings() }\n    \n    DashboardData(\n        user = userDeferred.await(),\n        settings = settingsDeferred.await()\n    )\n}\n```\n\n### 2. Exception Handling\n\nUse `CoroutineExceptionHandler` for top-level scopes, but rely on `try-catch` within suspending functions for granular control.\n\n```kotlin\nval handler = CoroutineExceptionHandler { _, exception ->\n    println(\"Caught $exception\")\n}\n\nviewModelScope.launch(handler) {\n    try {\n        riskyOperation()\n    } catch (e: IOException) {\n        \u002F\u002F Handle network error specifically\n    }\n}\n```\n\n### 3. Reactive Streams with Flow\n\nUse `StateFlow` for state that needs to be retained, and `SharedFlow` for events.\n\n```kotlin\n\u002F\u002F Cold Flow (Lazy)\nval searchResults: Flow\u003CList\u003CItem>> = searchQuery\n    .debounce(300)\n    .flatMapLatest { query -> searchRepo.search(query) }\n    .flowOn(Dispatchers.IO)\n\n\u002F\u002F Hot Flow (State)\nval uiState: StateFlow\u003CUiState> = _uiState.asStateFlow()\n```\n\n## Examples\n\n### Example 1: Parallel Execution with Error Handling\n\n```kotlin\nsuspend fun fetchDataWithErrorHandling() = supervisorScope {\n    val task1 = async { \n        try { api.fetchA() } catch (e: Exception) { null } \n    }\n    val task2 = async { api.fetchB() }\n    \n    \u002F\u002F If task2 fails, task1 is NOT cancelled because of supervisorScope\n    val result1 = task1.await()\n    val result2 = task2.await() \u002F\u002F May throw\n}\n```\n\n## Best Practices\n\n- ✅ **Do:** Use `Dispatchers.IO` for blocking I\u002FO operations.\n- ✅ **Do:** Cancel scopes when they are no longer needed (e.g., `ViewModel.onCleared`).\n- ✅ **Do:** Use `TestScope` and `runTest` for unit testing coroutines.\n- ❌ **Don't:** Use `GlobalScope`. It breaks structured concurrency and can lead to leaks.\n- ❌ **Don't:** Catch `CancellationException` unless you rethrow it.\n\n## Troubleshooting\n\n**Problem:** Coroutine test hangs or fails unpredictably.\n**Solution:** Ensure you are using `runTest` and injecting `TestDispatcher` into your classes so you can control virtual time.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,126,847,"2026-05-16 13:25:01",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"前端开发","frontend","mdi-language-html5","HTML\u002FCSS\u002FJavaScript\u002F框架相关",1,96,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"7b02f05b-7baa-4989-bffd-a6bc782516b7","1.0.0","kotlin-coroutines-expert.zip",1667,"uploads\u002Fskills\u002F4990589c-27a8-41f9-9d96-63af0b892165\u002Fkotlin-coroutines-expert.zip","4767d5a6d509f7dc9966ca6030dfba1cf075d55eed72a6afa9a5d69c186124ca","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":3379}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]