Saltar al contenido
Skillpedia
Programación general48 mil · #5012

kotlin-coroutines-expert

Qué hace

Esta guía enseña a usar las 'Coroutines' y el 'Flow' de Kotlin, que son herramientas para hacer varias tareas al mismo tiempo sin bloquear el programa. Muestra cómo organizar estas tareas, gestionar errores y probar tu código.

Cuándo usarla

  • ✓Cuando creas programas en Kotlin que necesitan realizar varias operaciones a la vez.
  • ✓Cuando trabajas con flujos de datos que cambian con el tiempo.
  • ✓Cuando depuras problemas con tareas canceladas o fallidas.

Link de la skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo hacer dos operaciones de red al mismo tiempo en Kotlin y gestionar posibles errores?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Utiliza un concepto llamado 'concurrencia estructurada', que asegura que las tareas se gestionen correctamente. También aprendes a usar 'Flow' para manejar datos secuenciales y a gestionar los errores de forma organizada.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

Kotlin Coroutines Expert

Overview

A guide to mastering asynchronous programming with Kotlin Coroutines. Covers advanced topics like structured concurrency, Flow transformations, exception handling, and testing strategies.

When to Use This Skill

  • Use when implementing asynchronous operations in Kotlin.
  • Use when designing reactive data streams with Flow.
  • Use when debugging coroutine cancellations or exceptions.
  • Use when writing unit tests for suspending functions or Flows.

Step-by-Step Guide

1. Structured Concurrency

Always launch coroutines within a defined CoroutineScope. Use coroutineScope or supervisorScope to group concurrent tasks.

suspend fun loadDashboardData(): DashboardData = coroutineScope {
    val userDeferred = async { userRepo.getUser() }
    val settingsDeferred = async { settingsRepo.getSettings() }

    DashboardData(
        user = userDeferred.await(),
        settings = settingsDeferred.await()
    )
}

2. Exception Handling

Use CoroutineExceptionHandler for top-level scopes, but rely on try-catch within suspending functions for granular control.

val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught $exception")
}

viewModelScope.launch(handler) {
    try {
        riskyOperation()
    } catch (e: IOException) {
        // Handle network error specifically
    }
}

3. Reactive Streams with Flow

Use StateFlow for state that needs to be retained, and SharedFlow for events.

// Cold Flow (Lazy)
val searchResults: Flow<List<Item>> = searchQuery
    .debounce(300)
    .flatMapLatest { query -> searchRepo.search(query) }
    .flowOn(Dispatchers.IO)

// Hot Flow (State)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()

Examples

Example 1: Parallel Execution with Error Handling

suspend fun fetchDataWithErrorHandling() = supervisorScope {
    val task1 = async {
        try { api.fetchA() } catch (e: CancellationException) { throw e } catch (e: IOException) { null }
    }
    val task2 = async { api.fetchB() }

    // A child failure does not directly cancel its siblings.
    // But an uncaught exception from await escapes the supervisor block and cancels it.
    val result1 = task1.await()
    val result2 = task2.await() // May throw
}

Best Practices

  • ✅ Do: Use Dispatchers.IO for blocking I/O operations.
  • ✅ Do: Cancel scopes when they are no longer needed (e.g., ViewModel.onCleared).
  • ✅ Do: Use TestScope and runTest for unit testing coroutines.
  • ❌ Don't: Use GlobalScope. It breaks structured concurrency and can lead to leaks.
  • ❌ Don't: Catch CancellationException unless you rethrow it.

Troubleshooting

Problem: Coroutine test hangs or fails unpredictably. Solution: Ensure you are using runTest and injecting TestDispatcher into your classes so you can control virtual time.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Examples are fragments: supply imports, repository interfaces, Android lifecycle dependencies and the installed coroutines version. Handle each awaited failure deliberately and rethrow cancellation. SharedFlow replay/buffer choices determine delivery while no collector is active; it is not a guaranteed event queue. StateFlow conflates state changes. Test cancellation and slow/absent collectors, not only happy paths. Official exception behavior.

Preguntas frecuentes

¿Qué es la 'concurrencia estructurada'?

Es una forma de organizar las tareas que se ejecutan al mismo tiempo, asegurando que se inicien y se detengan de manera controlada, como si formaran parte de un grupo.

¿Cuál es la diferencia entre 'StateFlow' y 'SharedFlow'?

'StateFlow' se usa para mantener el estado actual de algo (como el texto de un cuadro de búsqueda), mientras que 'SharedFlow' sirve para enviar eventos que pueden ocurrir (como un clic en un botón).

¿Por qué no debería usar 'GlobalScope'?

'GlobalScope' ignora la 'concurrencia estructurada', lo que puede hacer que las tareas sigan ejecutándose cuando no deberían, y provocar problemas y fugas de memoria.

Detalles

Descripción original del autor

Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.

repo: sickn33/agentic-awesome-skills

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#5012
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas