Kotlin / Reference example
Preserve Kotlin coroutine cancellation
Explicitly check coroutine cancellation in a long-running suspend function.
Kotlin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
suspend fun summarize(records: List<String>): List<String> {
val result = mutableListOf<String>()
for (record in records) {
currentCoroutineContext().ensureActive()
result += record.trim()
}
return result
}What matters
Structured scopes own task lifetimes. Do not swallow CancellationException or let a stale result overwrite a newer account or screen state.
Test these cases
- Parent scope cancellation
- Catch-all error handler does not swallow cancellation
- Stale UI request superseded
Sources and limits
This is a reference snippet, not a substitute for reviewing the full vendor API contract, concurrency rules or production threat model. Do not paste secrets into sample code.