https://kotlinlang.org logo
#compose
Title
# compose
z

zoha131

09/16/2020, 4:23 PM
Is it possible to create a ViewModel inside a Compose function? What would be the approach in Compose only app?
a

allan.conda

09/16/2020, 4:29 PM
they’re working on it. Right now it kinda works but there’s a bug on configuration change (state restoration does not work) if I’m not wrong.
z

zoha131

09/16/2020, 4:36 PM
Then I think wait for a while for that support and go with fragment for now. Thanks for the reply.
a

Andrey Kulikov

09/16/2020, 6:08 PM
it actually works. you can use
viewModel
composable function to get it. it will be a ViewModel bind to Activity or Fragment and will survive the screen rotation. the only limitation is that this viewmodel will not be destroyed when you stopped displaying this composable
z

zoha131

09/16/2020, 6:17 PM
yeah. my concern was to destroy
ViewModel
when the composable is out of the screen. is there any workaround to do that now?
a

Andrey Kulikov

09/16/2020, 6:20 PM
no. it will work when we release a navigation integration. in this case every navigation destination will have their own ViewModels scope
👍 1
a

allan.conda

09/16/2020, 6:23 PM
Ah, thank you for the correction 🙇 . I barely remember the ViewModel PR in the sample that got reverted 😄