Android ViewModel with Custom Arguments

Android Arch component has 2 types of view model. One is ViewModel and AndroidViewModel, differnce between those 2 is first one does not take any argument and latter one take application object as argument. Most of time we want to pass our custom argument to viewmodel and we can do that by extending ViewModelProvider.NewInstanceFactory() and in which we have to override the create method. Below is the example how we can create our CustomViewModelFactory

class CustomViewModelFactory(private val test: String) : ViewModelProvider.NewInstanceFactory() {

override fun <T : ViewModel?> create(modelClass: Class<T>?): T {
return LoginViewmodel(test) as T


In the activity class, we can create our view model with custom argument something like this

val viewModel = ViewModelProviders.of

The (retired) Pub(lication) for Android & Tech, focused on Development