Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Coroutine Cancellation and Timeouts | Getting Started with Coroutines
Kotlin Concurrency Fundamentals

bookCoroutine Cancellation and Timeouts

Desliza para mostrar el menú

Understanding how to cancel coroutines is essential for building responsive and robust applications. Coroutine cancellation allows you to stop ongoing work when it is no longer needed, such as when a user navigates away from a screen or when a network request becomes irrelevant. Unlike threads, coroutines use a cooperative cancellation model, which means that a coroutine must check for cancellation and respond appropriately. This is typically done by checking the isActive property or by using suspending functions that throw a CancellationException when the coroutine is cancelled. If a coroutine ignores cancellation signals, it may continue running and waste resources, so it is important to design your coroutines to cooperate with cancellation requests.

Main.kt

Main.kt

copy
1234567891011121314151617181920212223
package com.example import kotlinx.coroutines.* fun main() = runBlocking { val job = launch { try { repeat(1000) { i -> println("Coroutine is working: $i") delay(100L) } } catch (e: CancellationException) { println("Coroutine was cancelled!") } finally { println("Cleanup can be done here.") } } delay(350L) // Let the coroutine run for a short time println("Main: Cancelling coroutine...") job.cancelAndJoin() println("Main: Coroutine is cancelled and joined.") }

Timeouts are another important tool for managing long-running operations in coroutines. Without timeouts, a coroutine may hang indefinitely if, for example, it is waiting for a network response that never arrives. By applying a timeout, you can automatically cancel a coroutine if it takes too long to complete. This helps prevent your application from becoming unresponsive and allows you to handle such situations gracefully. You can use the withTimeout or withTimeoutOrNull functions to specify a maximum duration for a coroutine's work, ensuring that your code does not wait longer than necessary.

question mark

What happens to a coroutine when it is cancelled?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 5

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 2. Capítulo 5
some-alt