Arpit Shukla

08/23/2022, 2:37 PM
Hi everyone, I was going through the Jetpack Now In Android official sample. Really great sample but I couldn't find any example of navigation triggered by ViewModel there. In my apps I use Channels to send navigation events from ViewModel but Google seems to be recommending against this approach. I have gone through a lot of official samples but haven't found one which demonstrates how to handle navigation triggered by ViewModel. Does anyone know of any such sample (official or unofficial)? Maybe @Manuel Vivo

Csaba Szugyiczki

08/23/2022, 2:42 PM
I think there is nothing wrong with your approach. We are doing kind of the same in our apps, but instead of Channels we started to use SharedFlows. So we are connecting our ViewModels with the NavController in the MainActivity through a Singleton object that can be injected both in the Activity and all of our ViewModels.

Arpit Shukla

08/23/2022, 2:44 PM
Yeah, like the Channels approach never failed me (at least I never noticed). Just wanted to see an example of the approach that is being recommended everywhere because I find it quite hard to model my events as state.
the key part is that you don't send an event from the viewmodel called "navigateToHome". Instead you set the state to be "task is saved" and let the compose screen (in this case the nav graph) make the decision

Arpit Shukla

08/23/2022, 5:04 PM
Thanks for the example, so in this case we remove the current destination from the backstack while navigating. For the case where we move a step forward, we will also have to reset this boolean to false again, right? Otherwise when user comes back to this destination he will again be navigated??
@ppvi Could you please confirm this?


08/26/2022, 1:18 PM
you have to either reset the boolean or make sure that your viewmodel is recreated when you navigate back to the screen