Search code examples
kotlinmvvmviewmodelviewmodelproviders

How to create a custom viewModel provider class where i can avoid the viewModel cast?


Good Morning ;

I have this custom ViewModel factory class:

class AlreadyHaveAnAccountFragmentViewModelFactory (private val userDataSourceRepository: UserDataSourceRepository) :
ViewModelProvider.NewInstanceFactory() {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    return AlreadyHaveAnAccountViewModel(userDataSourceRepository) as T
  }
}

    /**
     * Initializing our ViewModel using a custom Factory design pattern
     */
    alreadyHaveAnAccountViewModel = ViewModelProviders.of(
        this,
        AlreadyHaveAnAccountFragmentViewModelFactory(
            RepositoryFactory.createApiRepository()
        )
    ).get(AlreadyHaveAnAccountViewModel::class.java)

The function create returns AlreadyHaveAnAccountViewModel(userDataSourceRepository) where AlreadyHaveAnAccountViewModel is my viewModel class. I need to create a custom viewModel factory class where i can pass AlreadyHaveAnAccountViewModel in parameter, or a way to avoid the nasty cast in the end.

help


Solution

  • I found the answer: With this methode you can avoid the cast in the end. This way you have only one ViewModelProvider in all your project.

    This will work with any class accepting a UserDataSourceRepository as constructor argument and will throw NoSuchMethodException if the class doesn't have the proper constructor.

    class AlreadyHaveAnAccountFragmentViewModelFactory (private val userDataSourceRepository: UserDataSourceRepository) :
    ViewModelProvider.NewInstanceFactory() {
    
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return modelClass.getConstructor(UserDataSourceRepository::class.java).newInstance(userDataSourceRepository) as T
      }
    }