Question on using ViewModels in Jetpack Compose --...
# compose
s
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?
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
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
thx @Ian Lake but what if i’m passing data into the view model?
google 1
i
The optional parameter to
viewModel()
is the factory used to create the ViewModel
s
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
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
onDispose
, not only when permanently destroyed
(that's the behavior of
collectAsState()
,
LaunchedEffect
)