简体   繁体   English

如何创建自定义 viewModel 提供程序 class 我可以避免 viewModel 演员?

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

Good Morning;早上好;

I have this custom ViewModel factory class:我有这个自定义 ViewModel 工厂 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. function 创建返回AlreadyHaveAnAccountViewModel(userDataSourceRepository)其中AlreadyHaveAnAccountViewModel是我的 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.我需要创建一个自定义 viewModel 工厂 class ,我可以在其中传递AlreadyHaveAnAccountViewModel参数,或者最终避免讨厌的演员表。

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.这样,您的所有项目中只有一个 ViewModelProvider。

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.这将适用于任何接受 UserDataSourceRepository 作为构造函数参数的 class 并且如果 class 没有正确的构造函数,则会抛出 NoSuchMethodException。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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