I'm a situation where I want my view model to comm...
# compose
n
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
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
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
"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