Why a viewmodel factory is needed in Android?

前端 未结 4 1659
傲寒
傲寒 2020-12-08 03:44

We have been discussing about this but we don\'t know the reason of creating a viewmodel factory to create a viewmodel instead of instantiate the viewmodel directly. What is

4条回答
  •  一生所求
    2020-12-08 04:29

    In short,

    if we need to pass some input data to the constructor of the viewModel , we need to create a factory class for viewModel.

    Like example :-

    class MyViewModelFactory constructor(private val repository: DataRepository): ViewModelProvider.Factory {
    
         override fun  create(modelClass: Class): T {
            return if (modelClass.isAssignableFrom(MyViewModel::class.java!!)) {
                MyViewModel(this.repository) as T
            } else {
                throw IllegalArgumentException("ViewModel Not Found")
            }
        }
    }
    

    Reason

    We cannot directly create the object of the ViewModel as it would not be aware of the lifecyclerOwner. So we use :-

    ViewModelProviders.of(this, MyViewModelFactory(repository)).get(MyViewModel::class.java)
    

提交回复
热议问题