sigmadelta
10/15/2024, 3:41 PM// ... when (screen) { ...
AppScreen.Account,
AppScreen.AccountViewProfile -> {
val vm = remember { AccountScreenViewModel(scope) }
val state by vm.observeStates().collectAsState()
when (screen) {
AppScreen.Account -> AccountScreen(state) { vm.trySend(it) }
AppScreen.AccountViewProfile -> AccountViewProfileScreen(state)
else -> throw IllegalStateException("Can't have a different screen here for Account")
}
}
In this example I have a screen called Account with a nested screen which shows more of the profile in details.
The problem is that I would like to persist (the state of) the ViewModel but as the recomposition happens, Compose creates a new instance of the ViewModel and the state gets cleared. So there are several ways to approach this issue that I thought of:
• Create a nested navigation where Appscreen.Account is the main entry point and has several AccountScreen.xxx destinations with its own router (did a similar thing for Login)
• Persist the state and recreate when Account(ViewProfile) is opened
• Move AccountViewModel outside of recomposition space (will live in memory with app lifecycle so not ideal)
Is there a better approach I’m missing? I’ve also considered the option of using Ballast Sync, but I’ll basically have the same issues here as the Source (AccountViewModel) will still be recreated with navigation.Casey Brooks
10/21/2024, 2:25 PMAccountRepository singleton, for example, then both screens can access the data from that Repository. And when building each screen, don’t consider the AppScreen.Account to be a screen with sub-screens for AppScreen.AccountViewProfile, make the header bit a reusable component that is included in both screens.