I'm trying to implement this scenario. I have a sign in screen with a sign in button. When the user clicks the button and gets authenticated, I send the user to the profile screen. The problem comes when the user hits the back button. Instead of existing the app, it goes back to the sign in screen, which is bad. If I have had activities, I have called finish()
in the sign in activity when going forward to profile activity, and when the user pressed back, it quits the app. How to do the same thing using navigation?
Asked
Active
Viewed 2,727 times
1

Joan P.
- 2,368
- 6
- 30
- 63
-
SIgn in screen is not an activity? – Karan Mehta Nov 24 '21 at 10:38
-
@KaranMehta No, are composables. I'm using Jetpack Compose. – Joan P. Nov 24 '21 at 10:41
2 Answers
2
You need to clear the navigation stack. You can do it in many ways.
For example, if you know that you only have a single item in your back stack, you can use popBackStack
:
navController.popBackStack()
navController.navigate(Destinations.Profile)
Or you can use popUpTo
and specify the first destination you wanna pop up, and add inclusive
parameter:
navController.navigate(Destinations.Profile) {
popUpTo(Destinations.Login) {
inclusive = true
}
}

Phil Dukhov
- 67,741
- 15
- 184
- 220
-
This is wrong. What i should do in case when i have NavHost?. I dont want to make my code more dirty. – Mopto Aug 28 '22 at 22:02
0
For creating viewModel instance every time when composable is started you need do this:
val viewModel= remember { MyViewModel() }
That's it. No need in popBackStack and e.t.c.
But i recommend you to found way to listen changes of data in your viewModel.
That will be more clear. JetPack Compose gives you another way how to write code and make Android application, so use it)

Mopto
- 370
- 5
- 6