Android Compose Navigation And Viewmodel Lifecycle
Solution 1:
The complete composition tree is rebuilt each time the screen is rotated, starting with setContent
.
In your source code, you subscribed to Navigator.route.observe
at every recomposition. And the "fix" is to convert LiveData
or Float
to composite state. You did this with Flow
+ collectAsState
, with LiveData
a similar method is called observeAsState
. Learn more about state in compose.
So, every time you rotated the device, navigate
was called.
navigate
does not change the current screen with the new destination. Instead, it pushes the new view onto the stack. So every time you navigate
- you push a new screen onto the navigation stack and create a model for it. And when you rotate the device without collectAsState
, you push another screen onto the stack. Check out more about compose navigation in documentation.
You can change this behavior with NavOptionsBuilder
, for example like this:
navController.navigate(route) {
if (route == "setup") {
popUpTo("setup")
}
}
The view models will be released when the corresponding views leave the navigation stack. If you click the Back button on the navigation bar, you will see that it has been released.
p.s. I personally find Compose much more flexible and convenient compared to SwiftUI, even though the first stable version was released only a month ago. You just need to know it better.
Post a Comment for "Android Compose Navigation And Viewmodel Lifecycle"