<https://developer.android.com/jetpack/compose/int...
# compose
a
https://developer.android.com/jetpack/compose/interop/compose-in-existing-arch#viewmodel says that ViewModels will still be tied to the lifecycle of the activity or fragment in which they were created. Is there any way to tie it to the "lifecycle of the composition" or should I use some DisposableEffects to reset view models' state?
c
If you only want it tied to the composition lifecycle, you don't really need to use the Androidx ViewModel class. That class really offers very little beyond automatic lifecycle management, the pattern itself is quite generic and can be done with a regular Kotlin class. Here's an example of doing just that https://kotlinlang.slack.com/archives/C01D6HTPATV/p1644259697620799?thread_ts=1644257413.142249&amp;cid=C01D6HTPATV
a
Okay, so you are passing a coroutine scope that is tied to composition and you are also tying the view model because it is created with a remember. Did I get it right ?
c
Yup. The ViewModel and CoroutineScope will both be controlled by the composition and stay around as long as the composable function does. If it goes away, then the CoroutineScope will get cancelled, along with any work in progress within the ViewModel, and the next time that function becomes active you'll have a new ViewModel instance with fresh state
s
If you are using Hilt and Jetpack Navigation, hilt-navigation-compose ties the ViewModel to the backstack.
a
But viewmodel has to created inside the composable right ? It can't be injected as param, right ?
s
Not sure if who you're addressing. If it's me, you would get the viewmodel by calling
hiltViewModel
a
I was addressing both approaches
c
I just use compose-nav, viewModel, and hilt and get all of this working for free. works great for my team.