Hello! I have an advice regarding compose navigati...
# compose
a
Hello! I have an advice regarding compose navigation and bottom nav bar. For example, I have two main roots (A, B) in the bottom nav, and based on the documentation I navigate between them using the saveState and restoreState (https://developer.android.com/jetpack/compose/navigation#bottom-nav). Each main root screen has their own Viewmodel, which are saved and restored each time I navigate A -> B and B -> A. I would like to call a refreshState every time I come back to A (the fun would simply update the VM UI state and re fetch data for some properties). I have found some workarounds but I do not like them a lot. Are there any specific recommendations / suggestions for these cases? I could probably avoid the saveState but I do not want to recreate the VM each time I navigate back to the viewmodel A. Thanks!
j
We accomplished this in our app by using a
LaunchedEffect(Unit)
. It will only run when the composable first enters composition. When you switch from view A -> B, view A should exit composition entirely. So when you switch back to A, the LaunchedEffect should run again.
d
I wondered how to do things in `Composable`s that would, in the old world, rely on the Lifecycle of a Fragment or Activity. I thought this documentation: https://developer.android.com/jetpack/compose/side-effects#disposableeffect on side-effects was invaluable.
a
Thanks @Joseph Hawkes-Cates and @dewildte. LaunchedEffect was my first idea, then I read the page about DisposableEffect and maybe I could update the state and refresh data when the observer enters on Start. I just need to test how updating the VMState at that point to Loading will impact the Composable A and if it causes multiple useless recompositions.
j
Yeah, good to keep recomposition in mind, but also don’t want to prematurely optimize there. If your VM refresh is updating the state a lot of individual times that could probably use some consideration, but otherwise I think it’s fair to go with the easiest solution and then check it with the recomposition counter in Android studio. That’s been my approach so far, anyway.
a
I agree @Joseph Hawkes-Cates, I will try the easiest approach and then analyzes recomposition and performance, thanks