I'm using the viewModel
composable function to give me an instance of my view model to work with, but I am wondering how I can enforce the framework to "recreate" the view model when needed.
I know this viewModel
function to behave similarly to ViewModelProviders, which created an instance of the view model when first invoked and then returned the same instance in case it already existed in memory. This allows to share the same instance of the view model across different fragments inside the same activity, etc.
I provide a factory to this method, because my view model has arguments in its constructor. What I never quite understood is how can I know a new instance will be created when the arguments change? For example I have a view model that lives on the activity level, so whenever the function is invoked, the same instance will be returned. The loggedIn user ID is in the argument of the VMs constructor. If the logged in user change, I need to recreate the view model. How can I trust the viewModel
function to understand this and give me a new instance instance of just returning the instance that already exists?
Example:
composable("MyRoute") {
val vm: UserViewModel = viewModel(
viewModelStoreOwner = LocalContext.current as AppCompatActivity,
factory = UserViewModelFactory(userId = loggedInUserId))
MyView(viewModel = vm)
}
Essentially what I need is to enforce the viewModel
function to use the factory again and create a new instance every time the loggedInUserId
changes, instead of returning a VM that was already created before.
How can I do this?
The viewModel()
function has a key
argument. Whenever key
changes, a new instance of ViewModel will be created, so you can use loggedInUserId
as a key.