Search code examples
androidkotlinviewmodel

Android kotlin passing dynamic arguments/parameters to ViewModel with ViewModelFactory


To transfer additional arguments/parameters for ViewModel we used ViewModelFactory. For example

ExtraParamsViewModelFactory(this.requireActivity().application, "some string value")

But when the ViewModel is created, I can’t change the arguments/parameters dynamically

 val myViewModel = ViewModelProvider(this, ExtraParamsViewModelFactory(this.requireActivity().application, "some string value")).get(SomeViewModel::class.java)

"some string value" becomes harcoded in fragment/activity class. In "some string value" I need to pass a date that is always different to ViewModel. In the fragment, the user selected a date, clicked on the button and this date as a arguments/parameters pass to ViewModel. Not suitable for this ViewModelFactory?


Solution

  • No need to pass arguments in ViewModel constructor. all what you need is a is a setter & warrper class depending on your use.

    I guess your ViewModel will have some thing like this

    
    data class CustomWrapper<T>(var value:T)
    class  VM : ViewModel(){
    
        private val stringValue = CustomWrapper<String>("")
    
        fun setNewStringValue(value:String){
            stringValue.value = value
            //TODO:: update stuff related to `stringValue` 
        }
    
    }
    

    then in your Activity/Fragment..simply call it..like this

    vm.setNewStringValue("new value")