2

I am getting this error. I have created ViewModelFactory class inside same ViewModel class file. When Im trying to initialise the viewmodel I am getting this error.

//Code written in fragment class in onCreateView after binding code//
homeViewModelFactory = HomeViewModelFactory((requireActivity().application as Application).repository)
        homeViewModel = ViewModelProvider(this, homeViewModelFactory)
                .get(HomeViewModel::class.java)


//Viewmodelfactoryclass//
class HomeViewModelFactory(private val homeRepository: HomeRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
            return HomeViewModelFactory(homeRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}


Josss
  • 229
  • 1
  • 4
  • 19

1 Answers1

4

The job of the ViewModelProvider.Factory is to create instances of your ViewModel class. At the moment all you're doing is returning a new instance of your factory.

Instead your return statement should probably be something like this:

return HomeViewModel(homeRepository) as T

This article covers the basics of a ViewModel in more detail.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44