https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hiring-french
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
j

Jesse Hill

08/02/2022, 7:09 PM
Is there a best practice for performing for handling a situation where you want to cancel/invalidate a flow if some input changes? The line of thought goes: 1. Get a flow representing the values for the term “a”. 2. Trigger a network call that results in updating the search with new results for “a”. 3. The collected flow now receives the updated data for the search “a”. 4. Start a new search for the term “abc”. 5. The previously collected flow is canceled and only the new flow with results for “abc” is collected. It works to hang onto the old Job where the initial flow is collected and then cancel that before collecting the new flow but that feels hacky. Playground Link (Code in the thread)
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

// Question: Is it hacky to hang onto the old Job where the first flow is collected
// and then to cancel it to achieve the desired results?

private val globalScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

val remoteData = listOf(
    "abc",
    "ab",
    "abb",
    "anb",
    "abcd",
    "abcdef",
    "ged",
    "maybe"
)

class SimpleCache {
    private var initial = setOf(
        "one",
        "two"
    )
    private val mutableStateFlow = MutableStateFlow(initial)

    fun resetCache() = mutableStateFlow.update { initial }

    fun search(term: String) =
        mutableStateFlow.asStateFlow().map { valuesSet ->
            valuesSet.filter { it.contains(term) }
        }

    suspend fun fetchData(term: String) {
        // Taking 3 to simulate an API where there are more matches for the
        // filter and a subsequent fetch can increase the results for a previous
        // call to `search`
        val newItems = remoteData.filter { it.contains(term) }.take(3)

        delay(500)

        mutableStateFlow.update { it + newItems }
    }

    var previousSearchJob: Job? = null
}

suspend fun searchWithCancellation(term: String, cache: SimpleCache) {
    globalScope.launch {
        cache.previousSearchJob?.cancel()

        cache.previousSearchJob = launch {
            cache.search(term).collect {
                println("For: $term")
                println("Collected: $it")
            }
        }
        launch {
            cache.fetchData(term)
        }
    }
}

suspend fun searchWithoutCancellation(term: String, cache: SimpleCache) {
    globalScope.launch {
        launch {
            cache.search(term).collect {
                println("For: $term")
                println("Collected: $it")
            }
        }
        launch {
            cache.fetchData(term)
        }
    }
}

fun main() {
    val cancellationCache = SimpleCache()
    val baseCache = SimpleCache()

    runBlocking {
        // This section is fine for the first flow but once there are
        // more than one being collected at the same time things break.
        println("Without Cancellation")
        searchWithoutCancellation(term = "a", baseCache)

        delay(1000)

        searchWithoutCancellation(term = "abc", baseCache)

        delay(3000)

        // This section prints the desired results
        println()
        println("With Cancellation")

        searchWithCancellation(term = "a", cancellationCache)

        delay(1000)

        searchWithCancellation(term = "abc", cancellationCache)

        delay(3000)
    }
    /* Output
        Without Cancellation
        For: a
        Collected: []
        For: a
        Collected: [abc, ab, abb]
        For: abc
        Collected: [abc]
        For: a <-- This collection is undesired and could come before or after the collection of "abc"
        Collected: [abc, ab, abb, abcd, abcdef]
        For: abc
        Collected: [abc, abcd, abcdef]

        With Cancellation
        For: a
        Collected: []
        For: a
        Collected: [abc, ab, abb]
        For: abc
        Collected: [abc]
        For: abc
        Collected: [abc, abcd, abcdef]
     */
}
g

George Theocharis

08/02/2022, 8:16 PM
No its not hacky to keep the job and cancel it and it's the correct approach. If you don't like it you can use ‘flatMapLatest’ instead as it automatically cancels the previous emissions.
n

Nick Allen

08/02/2022, 9:01 PM
Doing this yourself can lead to subtle errors. For example, you could collect an old result after you've collected a new result with your current code since
cancel
only starts the cancellation process. When you want to switch your
Flow
based on some change, look to the
*Latest
operators.
val searchTerm = MutableStateFlow("")
...
searchTerm
    .transformLatest {
        if (!it.isBlank()) {
            emitAll(search(it)) //Let's say search returns a Flow
        }
    }
    .collect { println("Collecting: $it") }
...
searchTerm.value = "a" //result will start emitting for search("a")

searchTerm.value = "abc" //result will cancel search("a") and start emitting for search("abc")
j

Jesse Hill

08/02/2022, 9:20 PM
Very interesting! That makes sense to look for the
*Latest
operators. Thanks for the example. I figured there’d be some sort of subtle issue with the way I had it. So since
cancel
only starts the cancellation process, does
cancelAndJoin
wait until the cancellation has been completed before continuing? It looks that way from the docs and because
cancelAndJoin
is a suspend function. I think that the
*Latest
would still make more sense for what I’m needing.
n

Nick Allen

08/05/2022, 12:26 AM
It's more complicated than that. Coroutines do not run in the order you call
launch
. If order matters, then you must use one coroutine with a loop (like a
Flow.collect
) or explicitly control it some other way like with a
CompletableDeferred
. Also, there's no guarantees between the launched code and the code that called
launch
.
job = launch { job.cancel(); ... }
could cancel then assign, or assign then cancel. And something like
previousJob.cancelAndJoin()
is dangerous because you could cancel the previously launched coroutine before it has a chance to cancel the one before that. And
cancelAndJoin
will only wait on the preview job, it doesn't wait on the job before that. If a coroutine is cancelled while calling
cancelAndJoin
then, it'll throw the cancellation exception immediately and not keep waiting.