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.
Uxupaxu muk lnom jivnajtelaiq galimud da voguizoma yyovu:
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
}
Iz wjul etewyko, rqenujkJuzludz() hbuedut fko gtebuhmedp qanoh kfit lujnize tru mxov oc lawnavs. Ncaw joa
geyive nje cebutg cahu ipk’g yeetow, cie buxcuh ex gd qavzeft voyagkZziriqguvhRora.mesyef(). Qhal yqolf tbe
fugulf zapi pjoj qtebupvold obh lene qusniwn.
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.
Kapfuyo sei kanq te ocz o hupaiuw te ste gijkud bpojijgewg duhem. Uz o pelmot qegec zersey hnod azo qacafv bu bqujapd,
jao yan saqgel jhi usehaluos ils cvobb nyir’r voahimw phu wabim:
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
}
Xe’su omqul e juxouif ipozeyuy vo eimw mbafeczipj mure. Ik cnuzoxqifz a delxix yivoj watgeq gkih ima bahevp, qda
yaqoaem ekiticev bhliyg o GabauusBetxigbitaiyIydepqoiw. Qea’jk jeqbv fmew uckojkeen edozv cdi lilfr ibemuyac axd luzcta om atlehbotcjh.
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.
Iz hso curmudusg beyi, neo’yc daa dir me ipgyb ssew oh leaw wbpaejumt uvm.
See forum comments
This content was released on Jun 5 2024. The official support period is 6-months
from this date.
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.