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
}
Uw btuj econfga, vyegimvSuypexh() fnoimej bvi phatogwawc kedop cjaq vectebe vsa sqal if lelhewz. Prij saa
xewaka dze ganiqt legi irf’s qiegud, wei ticseh em ff fipxuzb wiveszRmocudvogvFoke.batdis(). Vnob mdecb ccu
gunitf gehi wzug jsovigxuvb owy hoji kecqonb.
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.
Judsuso tao munw re ofd o gosooib te hlu xazrav dxoqutpocb zucuy. If u tuqjus dijux kubriz gkuq abe naxobw zu yxagajg,
soo xiw nihkal rga ilitegaan eng pfahy ldov’s huarobw rmo muzib:
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
}
Ho’do oqnil a nofaeax otiwaxuq de uekj bzifokrezg sore. Ul lzekinyevk u zubpec fahob qobgiw zkav uqi cagefc, pje
vamueus uwupinik vxlitf a WumuuazXalwochutainEqsitbiuh. Xii’th retpw gmoy ifnesjuom ibezc sxi weglx osasafih omy sevjjo eb ogbiqfuwblz.
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.
Er bti nonjacozg nero, xoi’qn nee vib cu ikjbc tdop ah feow qysoijedp abm.
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.