https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
a

Arun Joseph

02/15/2022, 8:53 PM
Is it possible to create a short lived android viewmodel within another larger viewmodel? For example, i have a view model for a view, I would like to create a new view model that lives from start button to stop button within the view.
t

Tim Oltjenbruns

02/15/2022, 9:04 PM
ViewModel is a pattern, and your ViewModels don’t have to inherit from androidx.lifecycle.ViewModel to follow the pattern
if your problem is retaining the object for the correct scope, that may be a problem for Dependency Injection
a

Arun Joseph

02/15/2022, 9:21 PM
Its like i want to have an extra scope for the inner view model.
t

Tim Oltjenbruns

02/15/2022, 9:34 PM
what if when you clicked that button, your “parent” view model updated a flow or livedata to contain this “child” viewmodel. (but the child would not inherit androidx viewmodel)
And then that child viewmodel had it’s own functions and flows/livedata
would that solve your issue?
Another option would be to make this child view a Fragment and give it a viewmodel
a

Arun Joseph

02/15/2022, 10:00 PM
Yes, i expect child view model to have independent state(live data) and methods. I would like to have parent & child view model to observe each others state(or livedata, i use compose) and send events to each other. Or both can communicate to data layers.
f

FunkyMuse

02/15/2022, 10:49 PM
View model inside another view model seems like a place for bugs and bad ideas, you can maybe have a shared object between those two view models that can tie their communication
a

Arun Joseph

02/16/2022, 5:58 AM
Its not exactly view model inside view model. But a big view or composable having a larger view model and a short lived view model from button press to button press
f

FunkyMuse

02/16/2022, 7:14 AM
That short lived view model can be that object
a

Arun Joseph

02/16/2022, 7:34 AM
I would like to take advantage of the scope, actions and state concept of view model for my special mode which exists between the button toggles.
3 Views