0

I try to create instance of ViewModel, but get an error.

java.lang.RuntimeException: Cannot create an instance of class com.example.event.ui.main.EventsViewModel

my code here to get instance:

viewModel = ViewModelProvider(this).get(EventsViewModel::class.java)

view model class

class EventsViewModel @Inject constructor(private val eventApi: EventApi): BaseViewModel() {

    val getEventsData = MutableLiveData<Response<List<Event>>>()

    fun getEventsData() {
        uiScope.launch {
            getEventsData.value = eventApi.getEvents()
        }
    }
}

1 Answer 1

0

Here, your ViewModelProvider is not aware of how to create EventsViewModel. If your ViewModel constructor was an empty constructor without any dependencies, it would work. However, if there is dependency or a parameter in your ViewModel constructor you need to provided a custom ViewModelProviderFactory.

If you want to check how/why custom view model factory is created you can check this codelab:

https://developer.android.com/codelabs/kotlin-android-training-view-model#7

If you want to employ dagger for injecting dependencies into your ViewModel, you can find an example in my sample repo:

https://github.com/hakanbagci/truemvvm

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.