hi all. I’m still grasping thinking in Compose, a...
# compose
j
hi all. I’m still grasping thinking in Compose, and I’m wondering if someone can guide me on the “correct” way to do this in the world of Compose. I have a parent screen which holds some master context (let’s say
someParentId
), and that screen is made up of some child Composables, and those Composables each have their own ViewModels. I would like to re-initialize those child ViewModels when
someParentId
changes, so that they re-load their data (and in turn recompose whatever is required) if I completely blow away the child ViewModels when
someParentId
changes and construct new ones, the corresponding UI must be recomposed every time, right? and that would be a very inefficient way to do it? so does this mean that the correct way would be to have ParentViewModel hold a reference to ChildA ViewModel and ChildB ViewModel, and when
someParentId
changes I can just get my existing child ViewModel references, and tell them to fetch the relevant new data? (hastily drawn pic for reference in case the relationships were unclear)
d
You could probably use a LaunchedEffect with
someParentId
as the key to trigger data reload in the ChildVIewModels, when
someParentId
changes..
LaunchedEffect(key = someParentId) {
childViewModel.reload()
}
This also means that you need to expose
someParentId
as an observable type (flow, rx) and the observe it as compose state. Optimally pass it as a function paramter all the way down to the child composables.
I'm not sure a viewmodel holding a reference to several other viewmodels is a good idea. If a ViewModel with a wider scope holds reference to viewmodels with a small scope, then you might have a memory leak when the smaller scoped viewmodels are disposed