I'm following a tutorial where a ViewModel extends an abstract class in order to use coroutines, this is the class that extends:
abstract class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCleared() {
super.onCleared()
job.cancel()
}}
And this is the ViewModel:
class ViewModel(application: Application) : BaseViewModel(application) {}
So in MainActivity I'm trying to instantiate the class like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this)[ViewModel::class.java]}
In the tutorial the guy perfectly does this but when I try to run the application it throws me an exception:
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.name.nameapp.main.viewmodel.ViewModel
I feel like I'm missing something can you guys point what it is, if you need more information I'll gladly post it
Your ViewModel
is child of AndroidViewModel
which requires an Application
object. So you will have to provide the Factory
class in order to instantiate the ViewModel
. Like so:
val viewModelProvider = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(application)
)
viewModel = viewModelProvider[MainViewModel::class.java]
If you are using the fragment library from Jetpack
implementation "androidx.fragment:fragment-ktx:1.2.5"
You can use property delegation like so:
val viewModel: ViewModel by viewModels()