https://kotlinlang.org logo
Title
a

aoriani

02/28/2022, 2:32 PM
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

Casey Brooks

02/28/2022, 3:12 PM
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&cid=C01D6HTPATV
a

aoriani

02/28/2022, 3:37 PM
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

Casey Brooks

02/28/2022, 4:29 PM
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

Sean Proctor

02/28/2022, 4:37 PM
If you are using Hilt and Jetpack Navigation, hilt-navigation-compose ties the ViewModel to the backstack.
a

aoriani

02/28/2022, 5:03 PM
But viewmodel has to created inside the composable right ? It can't be injected as param, right ?
s

Sean Proctor

02/28/2022, 5:07 PM
Not sure if who you're addressing. If it's me, you would get the viewmodel by calling
hiltViewModel
a

aoriani

02/28/2022, 6:38 PM
I was addressing both approaches
c

Colton Idle

02/28/2022, 11:45 PM
I just use compose-nav, viewModel, and hilt and get all of this working for free. works great for my team.