0

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?

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Its nice solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.