Question on using ViewModels in Jetpack Compose -- if I have:
Copy code
class TodoViewModel : ViewModel() {
var todoItems = mutableStateOf(listOf())
override fun onCleared { /* clean stuff up */ }
}
and then i remember it in my composable:
Copy code
var todoItems by remember { TodoViewModel().todoItems }
why isn’t
onCleared
called on the VM when navigation pops the composable back off the stack?
Sam
12/11/2020, 11:11 PM
I also tried in the composable:
Copy code
var model = remember { TodoViewModel() }
and then accessed the values via
model.todoItems.value
but still didn’t see
onCleared
fire on the VM. Is there any way to tap into
remember { }
lifecycle when popping off nav? Otherwise I’m forced to create Id’s for every view model and manually cleanup via
Composable { onDispose { /* cleanup */ } }
and it’s quite arduous.
i
Ian Lake
12/12/2020, 1:38 AM
You can't just directly call the constructor - that doesn't hook the ViewModel up to any of the underlying infrastructure. Instead, you should use
val model: TodoViewModel = viewModel()
s
Sam
12/12/2020, 2:17 AM
thx @Ian Lake but what if i’m passing data into the view model?
google 1
i
Ian Lake
12/12/2020, 4:13 AM
The optional parameter to
viewModel()
is the factory used to create the ViewModel
s
Sam
12/13/2020, 3:23 AM
Is there a more direct way of getting into the lifecycle of a
var x by remember { mutableStateOf() }
without using View Model interop? My original example was simplified, but I’m actually trying to subscribe to state changes from our Redux-based store, and then unsubscribe when the composable is popped off navigation. Is the View Model approach bringing in unecessary overhead for legacy techniques when there might be something more direct?
i
Ian Lake
12/13/2020, 3:53 PM
Compose doesn't have a direct signal for "this Composable is being permanently disposed", no. That being said, state change subscriptions should generally be removed in every