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
c

Colton Idle

08/16/2022, 12:43 AM
I have a Flow that's collected in my ViewModel. The Flow is actually from firestore which notifies me of updates. In my VM I update my snapshot state with the result of that Flow. My composable updates correctly. Life is good. But when I leave my app... the Flowable keeps on listening to updates. How do I do stop listening to my Flow once the app is backgrounded. It seems like it'd be easier if my flow was collected in the Composable, but there has to be a way to do this while collecting in my VM... right? Short example in thread
Sample:
val myFlow = flow { while (true) {
    delay(1000) 
    emit(1) } }
VM
var myState by mutableStateOf(0)

init {
  viewModelScope.launch {
    myFlow.collect {
      myState = myState.plus(it)
    }
  }
}
Composable
Text(text = vm.myState.toString())
tl;dr instead of simply pausing (which is what `LifecycleCoroutineScope.launchWhenStarted`/etc. do, leading to hot flows continuing to flow),
Lifecycle.repeatOnLifecycle
cancels and restarts the block, so it upstream is also cancelled while your app is not in the expected lifecycle state
c

Colton Idle

08/16/2022, 1:05 AM
Doesn't that force me to collect in my Composable vs collecting in my VM?
i

Ian Lake

08/16/2022, 3:17 AM
If you want collection to only be happening when your UI is present, then collecting in the ViewModel was always the wrong thing to be doing
That's true in Compose and in the non-Compose world. ViewModels work much better when they are cold flows that rely on something else (i.e., your UI) to actually make them active
f

Francesc

08/16/2022, 3:32 AM
you can have your viewmodel's flow stop collecting from firestore when the UI unsubscribes. That's also mentioned in the article linked above, so you can continue subscribing to the repository on your viewmodel, while stopping when the app is backgrounded
o

Oleksandr Balan

08/16/2022, 6:44 AM
So exposing a
State
from the VM is a "bad" thing? Because in such way Composable cannot "unsubsribe" from it?
s

Stylianos Gakis

08/16/2022, 8:17 AM
One idea is that you could expose that subscription to the UI so that it decides when this collection is happening. Remove the
init
block and expose it as something that the UI can subscribe to
class MyViewModel(
  val myFlow: Flow<Int> = flow {
    while (currentCoroutineContext().isActive) {
      delay(1000)
      emit(1)
    }
  },
) : ViewModel() {
  var myState by mutableStateOf(0)
  fun subscribeToFirestoreChanges(): Flow<Unit> {
    return flow {
      myFlow.collect {
        myState = myState.plus(it)
      }
    }
  }
}
Then on the UI simply turn the subscription on with the safe
repeatOnLifecycle
and decide on which state you want it to be on from (in this case
Lifecycle.State.STARTED
)
fun MyComposable(viewModel: MyViewModel) {
  val lifecycleOwner = LocalLifecycleOwner.current
  LaunchedEffect(viewModel, lifecycleOwner) {
    lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
      viewModel.subscribeToFirestoreChanges().collect()
    }
  }
  val text = viewModel.myState
}
Not sure if there are any problems with such an approach. I’ve done it once here and here since my
subscribeToAuthResultUseCase
was fetching for a status update every 1 second and only wanted that to happen while on screen. And this worked just fine for this use case👌
c

Colton Idle

08/16/2022, 3:03 PM
If you want collection to only be happening when your UI is present, then collecting in the ViewModel was always the wrong thing to be doing
Hm. Then I probably never want to be calling collect{} in a VM as I can't think of any reason when I want to be collecting something even when I'm not on the screen. I wonder if I can write a lint rule to prevent me from making this mistake.
f

Francesc

08/16/2022, 3:11 PM
there is nothing wrong with
collect
in the viewmodel, the business logic belongs there and the UI layer should not be talking to your data layer. What needs to happen is for your viewmodel to be aware when the UI is no longer collecting the state so that it can unsubscribe its own collectors
c

Colton Idle

08/16/2022, 3:33 PM
Hm. Yeah I'm trying to think of a convenient way to do that.
I think going off of @Stylianos Gakis that everything would work properly... but I'm actually having a hard time seeing if that'd work in my scenario. Only one way to find out I suppose!
f

Francesc

08/16/2022, 3:38 PM
you can use
stateIn
in your viewmodel to expose the UI state, and have it active only while subscribed, with an optional timeout (for configuration changes, for instance), so that it has a grace period before it disconnects
note that Stylianos' code is duplicating what the new
collectWithLifecycle
(or whatever it's called) does, so you don't need to do the repeat on lifecycle yourself
s

Stylianos Gakis

08/16/2022, 3:41 PM
Using
stateIn
would work with a
Flow
not with
State<T>
which I guess is not what Colton is going for. The new
collectStateWithLifecycle
API works when collecting a Flow not when you got compose State in your ViewModel afaik. I was trying to help for this specific case. Personally I also try to expose everything as a Flow anyway with
stateIn
in order to get this functionality for free. But it’s true that I haven’t managed to get that working for all the cases I’ve encountered.
f

Francesc

08/16/2022, 3:45 PM
another option is to use a disposable effect to start/stop the collection,
DisposableEffect(key1 = viewModel) {
    viewModel.onStart()
    onDispose { viewModel.onStop() }
}
this is a more manual approach but it would allow you to start/stop the collection when the composable enters/exits the composition
so you would move your
init
block to
onStart
and have an
onStop
where you stop your flows (you would get the returned
job
and
cancel()
that)
c

Colton Idle

08/16/2022, 3:46 PM
Definitely interesting to think about it that way since android lifecycles wont be there on desktop for example.
c

Colton Idle

08/16/2022, 3:47 PM
I will try a couple of these approaches out. I think overall I have to change my thinking a bit BUT in the meantime I would be fine with a quick and dirty implementation so that im not using a ton of data when the user isn't even looking at the screen.
@Francesc thanks for the article. I do like the simplicity and multiplatformness of just using an onStart and onStop methods.
Now I just gotta figure out if my firestore flows will actually cancel. I wonder how rotation effects it too. Maybe that's one reason to use the stateIn approach instead.
s

Stylianos Gakis

08/16/2022, 6:51 PM
The flows will in fact cancel if you don't keep it alive for that time in-between the rotation unless you either use stateIn as you said. If I understand it correctly, doing this https://kotlinlang.slack.com/archives/CJLTWPH7S/p1618760581089700?thread_ts=1618691113.058800&amp;cid=CJLTWPH7S may also make it so that the UI will not stop listening if you only do a rotation.
c

Colton Idle

08/16/2022, 6:57 PM
Gotcha. Okay so at least that part works as I imagined. and yeah, opting out of config changes is on my plate to do at some point. I do like to treat it as a quickway totest config changes (like wallpaper changes) which you can't opt out of.
Alright. group code review time... I kinda like this approach for its simplicity and the fact that it'll be an easy refactor from my current approach. VM:
var myState by mutableStateOf(0)
  
  val myFlow = flow {
    while (true) {
      delay(1000)
      emit(1)
    }
  }
  
  fun subscribeToFlow1(): Flow<Unit> = flow {
    myFlow.collectLatest {
      myState = myState.plus(it)
    }
  }
Composable screen: real easy!
vm.subscribeToFlow1().collectAsStateWithLifecycle(initialValue = Unit)
Essentially all I'm doing is wrapping my current flows in another flow and then moving them out of init {} and then calling collect in the composable screen.
f

Francesc

08/16/2022, 7:26 PM
why not apply
stateIn
to your
myFlow
? that would achieve the same result without the wrapper flow if you used "while subscribed"
c

Colton Idle

08/16/2022, 7:27 PM
Uhm. Not sure how that would look/work. Let me try?!
f

Francesc

08/16/2022, 7:27 PM
you can add to your flow
onEach { myState = myState.plus(it) }
c

Colton Idle

08/16/2022, 7:30 PM
Not sure I'm following anymore. How would I "apply
stateIn
to your
myFlow
?"
Fransec do you mean this?
fun subscribeToFlow1(): Flow<Unit> = flow<Unit> {
  myFlow.collectLatest {
    myState = myState.plus(it)
  }
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), Unit)
I'm not sure how I'd get rid of the wrapper flow {}
e

ephemient

08/16/2022, 7:54 PM
collecting one flow for the side effect on another flow - I don't like that at all
c

Colton Idle

08/16/2022, 7:57 PM
I agree that it looks a bit smelly, but I'm failing to see how else I'd do this.
i

Ian Lake

08/16/2022, 7:58 PM
If you're going to collect a Flow in the UI anyways, just collect the actual flow and skip the roundabout through State
f

Francesc

08/16/2022, 7:59 PM
I had this in mind
val myFlow = flow {
    while (true) {
      delay(1000)
      emit(1)
    }
  }
  .onEach { /* TODO */ }
  .stateIn(...)
c

Colton Idle

08/16/2022, 8:00 PM
@Ian Lake I agree and it looks that way in this example, but I guess throughout my application I have a bunch of other flows that are doing way more complex things... which results in some state being updated which my composables use. That's why I don't feel like just dumping all of that logic into the composable makes sense.
@Francesc I've never used onEach as that seems side-effecty (maybe my Rx java experience is leaking in here. which i was never great at Rx anyway, but I thought we should "avoid" side-effects.
f

Francesc

08/16/2022, 8:02 PM
onEach
is another way to collect your flow, when you use
launchIn
e

ephemient

08/16/2022, 8:03 PM
scope.launch { flow.collect { ... } }
==
flow.onEach { ... }.launchIn(scope)
to be clear
c

Colton Idle

08/16/2022, 8:04 PM
I've always avoided onEach (like I said, for rx java reasons) so thanks for highlighting that!
e

ephemient

08/16/2022, 8:05 PM
or
.collect { ... }
==
.onEach { ... }.collect()
and
scope.launch { .collect() }
==
.launchIn(scope)
, but you almost never see the parameterless
.collect()
c

Colton Idle

08/16/2022, 8:10 PM
Alright. Thanks everyone. I have ended up with this! VM:
var myState by mutableStateOf(0)

val myFlow = flow {
  while (true) {
    delay(1000)
    emit(1)
  }
}.onEach { myState = myState.plus(it) }
 .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), Unit)
Composable screen:
vm.myFlow.collectAsStateWithLifecycle(initialValue = Unit)
The only thing that I'm not in absolute love with is the fact that I have two initial values declared, once as the 3rd arg stateIn and another as the arg in collectAsStateWithLifecycle. No wrapper flows or anything!
I did find a case that I'm unsure how to convert and that's because collect {} == onEach{}.collect() but in some of my cases I'm using collectLatest. As an example. My user is exposed as a Flowable. and in a lot of my VMs I base the network call on the user.
init{
  viewModelScope.launch {
    userRepo.getUser().collectLatest { user ->
      apiService.getBooksForUser(user.id).collect {
...
I'll try working on the above though. maybe theres some collectLatest equivalent with onEach
f

Francesc

08/16/2022, 8:29 PM
your VM flow is a
StateFlow
, you don't need to define another init value in your composable if you expose it as a
StateFlow
userRepo.getUser().collectLatest { user ->
      apiService.getBooksForUser(user.id).collect {
use
flatmapLatest
instead
userRepo.getUser().flatmapLatest { user -> apiService.getBooksForuser(user.id) }
c

Colton Idle

08/16/2022, 8:33 PM
your VM flow is a
StateFlow
, you don't need to define another init value in your composable if you expose it as a
StateFlow
oh. neat
use
flatmapLatest
instead
awesome. theres a method for everything!
Just for the sake of completion.
userRepo.getUser().flatmapLatest { user -> apiService.getBooksForuser(user.id) }
didn't work but
userRepo.getUser().mapLatest { user -> apiService.getBooksForuser(user.id) }
did
f

Francesc

08/17/2022, 5:55 AM
flatmapLatest expects a flow, I guess your method is a suspending function instead, in which case map is correct
c

Colton Idle

08/17/2022, 2:39 PM
So much to learn. Thanks again for teaching!