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
n

Nathaniel Rowe

02/12/2022, 4:11 AM
I'm a situation where I want my view model to communicate a navigation event to the composition after completing some suspending work. For example, user types in a password, hits "login", and then the backend does some long-running work to do all the things necessary for authentication. My concerns are the following: • How to represent the nav event as part of the UI state. Simply setting a state property to "loginComplete = true" means it will be true still when the user navigates back (for whatever reason). • How to reliably cancel the work when the user leaves the composition, but not when the user changes orientations. For example, while the sign-in is happening, the user could press the back button, or navigate into an account recovery screen. If the user does either of these, I want any current sign-in activity to cancel (as opposed to it continuing while the user is off-screen). Navigating back should do this automatically by killing the view model scope, but navigating to the recovery screen doesn't do this. The sign-in can yield theoretically 3 results: normal success, verification required (nav to a verification screen), or sign in failed. While the sign-in is happening, I also want the UI state to be in a loading state. Specifically, my questions are: 1. What is best practice for cancelling any jobs/producers in the view model when navigating from a screen, without doing this on configuration changes and the like. I know of the
Activity.isChangingConfigurations
property, but is this reliable? Or should I just make sure to add a call to cancel jobs at every point where a navigation event happens, and make sure no navigation events happen higher up in the composition hierarchy? 2. What is the best practice for the view model communicating a nav event to the composable? I have a single UI state object for each screen, should I include a "nav event" property in the UI state? And how can I ensure this nav event only triggers up to one actual navigation event? I was thinking of creating an object which is like a "OneShotEvent" object, which has a "consume" method that suspends, and only consumes events that weren't already consumed. Or would a SharedFlow with no replay cache, or some application of producer channels be more idiomatic?
c

Colton Idle

02/12/2022, 6:30 AM
Note: Not an expert, but this is how I've come to learn some of this from Adam Powell and Ian Lake. Hopefully I do them some justice. Bullet point 1: Setting this as state does indeed seem to be the way to go. Your concern of what happens when the user hits back is valid at first glance but I think it's not really a concern. First, when you navigate away from the login screen the user really shouldn't be able to hit back and go back to the login screen. It should arguably be popped off the stack revealing the content underneath it. Second, having loginComplete is probably not so much what you want, instead you want to change the state of the appUser.isLoggedIn = true. Therefore more accurately representing the output of the network call. The network call isn't there to tell you that login is complete, it's there to tell you that a user is logged in. Bullet point 2: "while the sign-in is happening, the user could press the back button," In android 11 and lower, the back button finishes the activity which would kill the vm and therefore the coroutine/scope. In android 12, the back button doesn't finish the activity so I believe that yes the vm would keep the login call running in the background. "or navigate into an account recovery screen." I think that you might want to cancel the network call yourself then. I believe if you had the LoginScreenVM doing a long running operation and then you put another screen on top of it... then I think it'll keep that long running operation going. You could just make sure to cancel as you navigate away from this screen. This should be easy to test though. Launch a VM scoped coroutine that delays and logs every second. Actually let me do it myself.... one sec........ Okay back. Yeah. On my login screen VM I put an init block with a delay and a log. Then I clicked into my reset password screen and the logs kept coming. as I expected. "Navigating back should do this automatically by killing the view model scope, but navigating to the recovery screen doesn't do this." Whoops. Okay. So you knew this. Uhm. Yeah. I guess this makes sense. a VM has a verrrry simple lifecycle. You can "complicate" it if you want (I think ive seen people essentially pass stuff into the VM so its lifecycle aware) but I would just cancel the network call on any navigation event essentially and call it a day. /shruggie This does kinda point out why state > events for stuff like navigating based on state because you don't have to worry about not having your screen up at the time and then it missing an event to navigate. For example. User hits login. Your server is taking forever for some reason. User remembers they have to call their mom. They go home. Open the phone app. Talk for 5 minutes about how your day was and nothing really changed since yesterday. Some of your coworkers are annoying you. etc etc. Then you tell her you love her and end the call. Go back to the app, and bam the state should be updated already and so when you open up the app, on the first recomposition the launchedEffect will be called and you'll be navigated. "The sign-in can yield theoretically 3 results: normal success, verification required (nav to a verification screen), or sign in failed. While the sign-in is happening, I also want the UI state to be in a loading state." Normal success I would represent with app wide state (i.e. appUser.loggedIn. signInFailed would be a local state to that VM. While signin happening, could also be a state for just that vm. like awaitingResponse = true.
for your #2: The tldr is not to have an event stream. Represent it as state. Some things that will be worth reading for you are: https://developer.android.com/jetpack/guide/ui-layer/events#compose_1 (it literally shows the suggested approach from the android team for login screens) https://developer.android.com/jetpack/guide/ui-layer/events#other-use-cases (warnings on why not to use events) Ian lakes case study on login with nav arch component

https://www.youtube.com/watch?v=09qjn706ITA&t=286s

(still applicable to compose arch nav component) ALSO! I'm writing a blog post on this. so stay tuned!
❤️ 1
n

Nathaniel Rowe

02/12/2022, 10:02 PM
So, I think you are latching on to the traditional login process too much. I was just trying to give an example, in my case the login process is way more complex than normal. On bullet point #1: the "login" example was just that, an example. In reality, I have a situation where the user types in their username, hits next, and then an API call is made to determine which login screen to show (either the normal screen, or open a web view for SSO). In the normal case, they see a password entry screen, but should be able to hit back and see the username they originally typed in. So the original username-entry screen should remain on the stack. Simply setting a state does in fact cause you to "bounce back" to the password screen, as this is what I was experiencing. It seems the solution is that I need to be able to "consume" the event part of the state, so that the view model's state resets to a non-navigated state. I'd like to ensure that updating the state to a "nav forward" state can only result in a single navigation. One way to do this is to make a property on the ui state which is a nullable channel. If null, there is no nav event to make. If not null, then in a launched effect, observe the channel until a nav event comes through. When the event is received, the channel ensures no one else receives it, as is the nature of channels. Another way to do this is simply to have a view model method which is like "reset nav events". In a launched effect, watch the nav state property. When it's set to something that results in a navigation, before actually navigating, call "viewModel.resetNavState()" to un-do that and ensure no one else sees the event. I was mostly asking about this to see if anyone else had actual experience with it, or opinions on what is more idiomatic. Channels feel more "correct" but also a bit "over-engineered". On bullet point #2: I think I have the back functionality sorted out, activity has nothing to do with it, my view models are tied to the navigation destination, and hitting back does pop the destinations off the back stack, killing the view model, ending that scope. Anyway, thanks for the help, sounds like I just need to hack this together. I'll just do whatever works.
c

Colton Idle

02/12/2022, 10:20 PM
"I think you are latching on to the traditional login process too much." That's the example you gave so yes I used that example. 😂 Also, even without login most of what I said still holds true. Good luck