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
r

ritesh

04/12/2022, 6:49 PM
👋 I came across this article recently, the part
Safe Flow collection in Jetpack Compose
@Composable
fun LocationScreen(locationFlow: Flow<Flow>) {

    val lifecycleOwner = LocalLifecycleOwner.current
    val locationFlowLifecycleAware = remember(locationFlow, lifecycleOwner) {
        locationFlow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
    }

    val location by locationFlowLifecycleAware.collectAsState()

    // Current location, do something with it
}
Do we need it, while collecting states? Isn't
Composables
have their own life-cycle? and we need not to worry about how the lifecycle of host it's contained in, while collecting flows?
a

Adam Powell

04/12/2022, 6:58 PM
Things don't leave the composition when your activity moves to the background. If that matters for your data collection lifecycle then a tool like this can be useful
r

ritesh

04/12/2022, 7:23 PM
That should be probably okay i guess when you are collecting
state-flows
if my app moves to background, new
emit
from api or so before moving to background, will just update the view, compose or re-compose while in background.
Making
sate-flow
collection, host life-cycle aware, how composable gets notified when there is change in lifecycle from
STARTED
to
PAUSED
or so, considering the mentioned scenario where app goes in background and then comes back to foregroud.
Probably an example or use-case can clarify 🙂
a

Adam Powell

04/12/2022, 7:34 PM
if your upstream flow is a cold flow that causes work to be performed while it is actively collecting, then this matters to you. For example, if you had a flow that maintained an open server connection receiving events regularly, that is not the sort of thing you want to leave running in the background
I think one of the examples also used is something like a flow for GPS location
leaving the GPS running is very costly for the user's battery life
r

ritesh

04/12/2022, 7:40 PM
Thanks for the explanation Adam, makes sense in above use-cases! I was more thinking or asking in terms
StateFlow
which is a hot-stream, and whose emission is usually based on some click event or say one-shot api call, in most of the apps or screens. In above scenario it's probably an over-kill IMO, and doesn't makes much to make this collection host life-cycle aware.
I am basically looking for a strong-reason for making
state-flow
collection - host activity life-cycle 😄 aware unless required. And in most of the use-cases we probably don't need it i guess!
cc: @Manuel Vivo
Adam, I came across this thread I should have searched before asking 🙂 Few takeaways from this conversation i wanted to clarify -
If you're using the default Recomposer that gets configured when you use ComposeView or ComponentActivity.setContent then recompositions will stop when the lifecycle does and start again when the lifecycle does.
As this is the default behavior, one should not worry about re-composition when app is in background, re-comp stops when it's host life-cycle does. Considering above, it's more of a concern if you are collecting cold-stream (few examples like location update or open socket connection etc...) or any stream which is effectively updating some state even if the app is in background and to avoid that collecting flows using
.flowOnLifecycle
makes sense. But, if you have something like StateFlow (a hot stream), whose emission is not very frequent but limited to one-shot api-calls etc..
.flowOnLifecycle
could be totally avoided, as re-comp won't take place when app is in back-ground as it adheres to the host lifecycle and updating state is fine.
a

Adam Powell

04/13/2022, 1:02 AM
I would expect that in the future recomposition will likely be slowed way down in frequency (~1Hz or so) rather than stopped entirely when the host lifecycle is stopped; there are cases where recomposition can be used to stop work too (e.g. removing an effect collecting a cold stream under some circumstances) so stopping it entirely probably isn't the ideal long-term behavior
👍 1
and if you have something like a StateFlow that isn't a
.stateIn(..., SharingStarted.WhileSubscribed...)
then you should also ask why it's not a
mutableStateOf
instead 🙂
r

ritesh

04/13/2022, 1:27 AM
Sure, Is there a benefit or reason when one should mostly prefer
mutableStateOf
instead of
StateFlow
- i know that somewhere down the line when we do
collectAsState
it converts to
State<>
I have been using
StateFlow
for every screen (even if i don't need to use transformation or other operators) and have found it pretty handy when it comes to testing using libs like
turbine
etc.. Say, i don't want to use operators on flows, i should be prefer
mutableStateOf
? Probably wrap all my
mutableStateOf
inside one class and then expose it to composable?
a

Adam Powell

04/13/2022, 1:40 AM
there are some other threads here and there on the topic as well; we might publish some additional guides down the line since it comes up fairly frequently
a few patterns we've been playing with make it nice to work with snapshots when cold sources are upstream as well; nothing to share as a library there yet though
👍 1
r

ritesh

04/13/2022, 1:44 AM
we might publish some additional guides down the line since it comes up fairly frequently
that would be great! This thread has detailed explanation! Thanks Adam!
👍 1