0

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

Firas Chebbah
  • 415
  • 2
  • 12
  • 24
  • I am not really sure what you want to do, custom ViewModelFactory with parameter your ViewModel (AlreadyHaveAnAccountViewModel)? Why you need this? – MrVasilev Nov 01 '19 at 14:20
  • using this methode i need to create a new ViewModelProvider each time i create a new ViewModel, i want to create a custom viewModel where i can use it with any viewModel in my project – Firas Chebbah Nov 01 '19 at 14:21
  • i want to avoid the nasty cast in the end : – Firas Chebbah Nov 01 '19 at 14:24

1 Answers1

0

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
  }
}
Firas Chebbah
  • 415
  • 2
  • 12
  • 24