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
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
c

Colton Idle

12/15/2021, 4:30 AM
I encounter this pattern a lot
viewModelScope.launch {
 val thing: String = someSuspendFunctionThatReturnsAValue()
 aMethodCallThatIsAFlow(thing).collect {
   if (it.status == "SUCCESS"){
    state.success = true
    //should I call job.stop() here?
   }
 }
}
My problem is that I want the flowable to stop collecting. Can I just save a ref to the call to launch and then call stop()? Or is starting a flowable in a coroutine scope frowned upon in general?
a

Adam Powell

12/15/2021, 4:42 AM
aMethodCallThatIsAFlow(thing).first { it.status == "SUCCESSFUL" }
state.success = true
?
(also returns the object that matched)
c

Colton Idle

12/15/2021, 4:46 AM
In my case, aMethodCallThatIsAFlow is a firebase firestore snapshot listener, where I'm listening for a document to be updated into the "success" state. I don't think first() would work here? I'm going to give it a shot though. Maybe first() would work if I wrapped it in a runBlocking?
Something is definitely funky with doing it my way because the second time I press my button (which triggers the vMS.launch{}, I get two Log statement prints inside of the if (status == "SUCCESS"), but the first time I land here I only get one log statement. So far though my code above "works", it just doesn't seem "right"
a

Adam Powell

12/15/2021, 5:13 AM
Why wouldn't first work? It's basically just a filter/take(1)/collect
c

Colton Idle

12/15/2021, 5:21 AM
Hm. It didn't work, for me. Let me paste what I had.
This is what I currently have. It "works"
fun confirmEvent(successEvent: () -> Unit) {
  viewModelScope.launch {
    var response = repository.getIdFromServer()

    if (response.isValid) {
      var response2 = repository.getObjectWithCurrentStatus(response.data.id)

      //Keep listening to changes on the server until the status changes from IN_PROGRESS TO SUCCESS
      response2.collect {
        if (it.status != "IN_PROGRESS") {
          if (it.status == "SUCCESS") {
            successEvent()
          } else {
            state.errorDialog = true
            state.errorDialogText = "Error 2: " + it.status
          }
        }
      }
    } else {
      state.errorDialog = true
      state.errorDialogText = response.errorText
    }
  }
}
Switching over to
first
does not work. But maybe I did it wrong?
fun confirmEvent(successEvent: () -> Unit) {
  viewModelScope.launch {
    var response = repository.getIdFromServer()

    if (response.isValid) {
      var response2 = repository.getObjectWithCurrentStatus(response.data.id)

      //Keep listening to changes on the server until the status changes from IN_PROGRESS TO SUCCESS
      val waiting = response2.first {(it.status == "SUCCESS")}
      
        if (waiting.status != "IN_PROGRESS") {
          if (waiting.status == "SUCCESS") {
            successEvent()
          } else {
            state.errorDialog = true
            state.errorDialogText = "Error 2: " + waiting.status
          }
        }
      }
    } else {
      state.errorDialog = true
      state.errorDialogText = response.errorText
    }
  }
}
@Adam Powell Actually wait. it seems to work now? I swear the first time I launched it it didn't work. I swear I just freakin hit this issue in AS again. https://issuetracker.google.com/issues/191997469 Lol. Anyway. Im going to run some more tests, but yes first{} seemed to have done exactly what I was expecting it to do. One last thing though (and i guess maybe its not worth the hypothetical question), but how would I do this if
first
didn't exist and
collect
is all I had?
Would i go the route that I said before of cancelling/stopping the coroutine scope?
I wonder if this would just be the right approach
viewModelScope.launch {

        beaconService.streamTest().collect {

            //Do something then
            this.coroutineContext.job.cancel()

        }
}
f

Francesc

12/15/2021, 6:28 AM
The scope is the viewmodel's so you shouldn't cancel it, you should get the job and call cancel on that instead. Cancelling the scope would cancel all coroutines and once cancelled you can't launch again
I read also that is customary for functions that launch a coroutine and return immediately to be defined as extensions on coroutine scope
c

Colton Idle

12/15/2021, 6:33 AM
wait. cancelling the scope cancels all coroutines. interesting. @Fran so what you're saying is that
this.coroutineContext.job.cancel()
should work fine then? Because I'm cancelling the job? or should I do
val job = viewModelScope.launch {

        beaconService.streamTest().collect {

            //Do something then
            job.cancel()

        }
}
f

Francesc

12/15/2021, 6:34 AM
Yes, but launch returns a job, you can get it there
Right
But the first operator is the right way for your scenario
c

Colton Idle

12/15/2021, 3:03 PM
So I can't reference the job from inside the job. so im kinda back at square 1. lol
tl;dr: throw
c

Colton Idle

12/15/2021, 3:39 PM
Interesting. Yeah, essentially I want to
return
out of the flow, but I guess
throw
is what I should use.
who knew this would get so confusing. Interestingly enough
this.coroutineContext.job.cancel()
did seem to work also.
a

Adam Powell

12/15/2021, 3:43 PM
it also has some rather nasty other side effects
c

Colton Idle

12/15/2021, 3:46 PM
oof. okay.
throw
it is.
a

Adam Powell

12/15/2021, 3:47 PM
all
cancel()
is doing is causing other suspend points and cancellation checks later to throw a
CancellationException
, and as the inner callee you don't know how broad that
job
is
if you consider what flows are and how they work, throw is the only thing that can do what you want here. Consider a flow that iterates over a collection:
flow {
  for (item in list) {
    emit(item)
  }
}
how can something called by
emit
cause that
for
loop to stop iterating other than by throwing?
or add in resource management:
flow {
  val thing = openThing()
  try {
    while (thing.hasMore()) {
      emit(thing.readMore())
    }
  } finally {
    thing.close()
  }
}
how do you make this code stop reading this resource before it's finished and properly clean up?
c

Colton Idle

12/15/2021, 3:56 PM
I guess using a standard language construct like throw makes sense when you put it that way. I guess I just associate throw with something scary lol and so it feels "wrong" but i appreciate you teaching me!
👍 1
a

Adam Powell

12/15/2021, 3:57 PM
yeah decades of, "don't use exceptions for control flow" beaten into your skull will do that 🙂
sort of a side rant but this sort of thing is why it makes me sad when people get religion about returning result types to the exclusion of throwing exceptions at all. There are good reasons to dislike APIs that use exceptions inappropriately but what they do is incredibly useful when you need to say, "I could not meet the contract of what you asked me to do" up layers of the call stack
c

Colton Idle

12/15/2021, 4:07 PM
funny you mention that, as thats an upcoming issue Im likely to post about in #getting-started
thank you adam! cheers
👍 1
a

Adam Powell

12/15/2021, 4:13 PM
https://www.artima.com/articles/the-trouble-with-checked-exceptions is a good piece of reading in the general space
n

Nick Allen

12/15/2021, 5:14 PM
FYI: cancel within launch does not cancel the parent scope
viewModelScope.launch { // Receiver of lambda is CoroutineScope for just this launched Job
    this.coroutineContext.job.cancel() //Does not cancel viewModelScope, just cancels the launched Job
    cancel() // Or you can just call it on the scope :)
}
And if you need to terminate the flow early, but
first { ... }
isn't enough,
takeWhile { ... }
or
transformWhile { ... }
may be useful so you don't need to deal with the exceptions yourself.
a

Adam Powell

12/15/2021, 6:49 PM
cancel within launch does not cancel the parent scope
while this is technically correct, cancelling your current scope is very often something you do not want to do. Consider:
suspend fun doAThing() {
  someFlow.collect {
    if (it % 2 == 0) coroutineContext.job.cancel()
  }
}

// ...
doAThing()
doSomethingElse() // does this run? does it finish its work? why or why not?