Pablo
06/21/2024, 12:01 PMcompanion object {
val factory : ViewModelProvider.Factory = viewModelFactory {
initializer {
MyViewModel(
MyApplication().container.repository
)
}
}
}
And later using that companion object variable like this:
viewModel: MyViewModel = viewModel(factory = MyViewModel.factory)
But they don't explain how to pass a simple String parameter 😕 How can I adapt that code for receiving a String as a parameter and passing it when initializing the viewModel?Michael Marshall
06/21/2024, 12:32 PMPablo
06/21/2024, 12:39 PMPablo
06/21/2024, 12:40 PMMichael Marshall
06/21/2024, 12:49 PM@Composable
fun MyScreen(
param: String,
viewModel: MyViewModel = viewModel {
MyViewModel (
param = param,
repo = MyApplication().container.repository,
)
},
)
Some of the navigation libraries handle it for you by making navigation arguments available via the SavedStateHandle
in the VM.Michael Marshall
06/21/2024, 12:50 PMPablo
06/21/2024, 1:45 PMPablo
06/21/2024, 1:46 PMPablo
06/21/2024, 1:46 PMPablichjenkov
06/21/2024, 3:51 PMassisted injection
as it is known too.Pablo
06/21/2024, 3:59 PMPablo
06/21/2024, 3:59 PMPablo
06/21/2024, 3:59 PMPablichjenkov
06/21/2024, 4:18 PMviewModel { factory = MyFactoryGlobalReference }
function was created with assisted injection in mind.
I believe that if you are using the compose navigation library, and SavedStateHandle in your ViewModel(savedStateHandle). The ViewModel will receive the arguments from the navigation in the savedStateHandle.
But I haven't used that so I can't provide much details.Mark Murphy
06/21/2024, 4:53 PM