简体   繁体   中英

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

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM