dimsuz
03/21/2022, 1:35 PMcomposable("/my/route") {
val value = remember { HeavyValue() }
MyScreen(value)
}
Whenever I navigate back and then forward to this screen, I'd like HeavyValue
to be recreated. In code above it is created once and persists:
push/pop/push <-- will get the same valuechansek
03/21/2022, 1:37 PMfun MyScreen() {
val value = remember { HeavyValue() }
MyScreen(value)
}
fun MyScreen(value: HeavyValue) {
...
}
dimsuz
03/21/2022, 1:41 PMhfhbd
03/21/2022, 1:48 PMremember
, which invalides the calculationIan Lake
03/21/2022, 1:56 PMZach Klippenstein (he/him) [MOD]
03/21/2022, 2:15 PMrememberSaveable
should be dropped at that point. Otherwise it would end up leaking a ton of memory for destinations that are never pushed back onto the stack.Ian Lake
03/21/2022, 2:40 PMIan Lake
03/21/2022, 2:44 PMdimsuz
03/21/2022, 2:59 PMViewModel
there, that's the HeavyObject
I'm talking about 🙂. And as per example above, that remember
will never be disposed.dimsuz
03/21/2022, 3:00 PMadd a key toyep, but what would that key be? Trying to figure this out. Currently I have an idea to try, which invalides the calculationremember
navBackStackEntry
(which is given to the composable
body as a keyIan Lake
03/21/2022, 4:21 PMcomposable
in your code snippet? That looks like an Arch Component 🙂Ian Lake
03/21/2022, 4:23 PMrememberSaveable
(not the objects themselves, the saved state) and the entire ViewModel
object. You really need to put your HeavyObject
in a ViewModel if you want the whole object to exist the entire time period that the NavBackStackEntry existsdimsuz
03/21/2022, 4:26 PMIan Lake
03/21/2022, 4:52 PMprivate class StashViewModel<T>(val stashed: T): ViewModel()
@Composable
fun <T> stash(stashInitializer: () -> T): T {
// Use the lambda based constructor introduced in 2.5.0-alpha03
val stashViewModel = viewModel {
StashViewModel(stashInitializer())
}
return stashViewModel.stashed
}
// Use it like
val value = stash { HeavyValue() }
Ian Lake
03/21/2022, 4:53 PMSavedStateHandle
and will support custom Savers here in the next release thanks to https://issuetracker.google.com/195689777 - not sure what your custom ViewModel has to support that casedimsuz
03/22/2022, 10:33 AM