Coroutine Cancellation and Timeouts
Svep för att visa menyn
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
1234567891011121314151617181920212223package 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.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal