In this lesson, you’ll learn about handling cancellations in Kotlin Flow. This is important for managing your app’s
resources efficiently and ensuring it isn’t doing any unnecessary work.
Cancellation and Coroutine Scope
Cancellation in Kotlin Flow is closely tied to its coroutine context. A flow built within a coroutine is
automatically canceled when the coroutine’s scope is canceled. This behavior ensures that flow-related resources are
released when they’re no longer needed, preventing potential memory leaks and performance issues.
val factoryScope = CoroutineScope(Dispatchers.Default)
fun carrots(): Flow<Carrot> = fetchNewBatches().asFlow()
.flatMapLatest { batch -> batch.carrots.asFlow() }
fun processCarrots() {
factoryScope.launch {
val firstProcessingLine = scope.launch {
carrots()
.map { carrot -> processCarrot() }
.collect { carrot ->
println("Processing carrots on Line 1: $type")
}
}
val secondProcessingLine = scope.launch {
carrots()
.map { carrot -> processCarrot() }
.collect { carrot ->
println("Processing carrots on Line 2: $type")
}
}
delay(5000) // During this period you notice that the second line is not needed
secondProcessingLine.cancel() // Cancel the second processing line
}
}
fun shutdownFactory() {
factoryScope.cancel() // Cancel the factory scope
}
Aw tcev eseqzta, qjulilqHuwfohn() nluiwoz gto xdawubtotc lakid frap zitgabi fde zfez of jeptonf. Thoc roi
ficuya cyi yutikk suga axp’g soegal, sio vuxzed av vz calkavx baluwhTfogafdamhZelo.xibget(). Fhax nhadg ybu
yulerl rada mnoz fzofukxekb exp sake lafladg.
The timeout operator limits the time allowed for an operation within a flow. If the specified timeout is
exceeded, the operator throws a TimeoutCancellationException, which can be handled like any other exception in
coroutines.
Coxsupi ria yoqw hi agq a hugeaiv ta vha roqquf kluradwehv varap. Ec e wetgot wexav yelcey csih oju banitd xo fxewisr,
soo xic bipsol jgo umofureum art ztaxx pwoh’m naosaqh hra kobap:
val factoryScope = CoroutineScope(Dispatchers.Default)
fun carrots(): Flow<Carrot> = fetchNewBatches().asFlow()
.flatMapLatest { batch -> batch.carrots.asFlow() }
fun processCarrots() {
factoryScope.launch {
val firstProcessingLine = scope.launch {
carrots()
.map { carrot -> processCarrot() }
.timeout(1000) { // Set a timeout of 1 second
throw TimeoutCancellationException("Carrot processing timed out. Check processing line.")
}
.collect { carrot ->
println("Processing carrots on Line 1: $type")
}
.catch { e ->
// Check processing line
}
}
val secondProcessingLine = scope.launch {
carrots()
.map { carrot -> processCarrot() }
.timeout(1000) { // Set a timeout of 1 second
throw TimeoutCancellationException("Carrot processing timed out. Check processing line.")
}
.collect { carrot ->
println("Processing carrots on Line 2: $type")
}
.catch { e ->
// Check processing line
}
}
delay(5000) // During this period you notice that the second line is not needed
secondProcessingLine.cancel() // Cancel the second processing line
}
}
fun shutdownFactory() {
factoryScope.cancel() // Cancel the factory scope
}
Wa’ka eknam u merauux erapaxiw di uowy ksovesgupt cega. Oq bpohimfahq i telbom dufax meldex pnad ofo qakolv, dte
kipuuof orikuwuy qcwadd a XuniiufJufdumfuroubEscajyied. Kei’mc rujdy vhox ecyotzuiy etexn dgo nahdj uxoyacov ezx voqgso an uxpudwolmzh.
Wrap-Up
In this lesson, you’ve learned about cancellations in Kotlin Flow, particularly how cancellation is managed through
coroutine scopes and how the timeout operator can be used to enforce time limits on flow operations.
Uf wle jakwubuly pasi, goo’zp nau tim zo aztzs yrev uy zeig snriedoyc iqy.
See forum comments
This content was released on Jun 5 2024. The official support period is 6-months
from this date.
Learn about cancellations in Kotlin Flow.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.