Search code examples
androidkotlinandroid-viewmodel

Why viewmodelfactory not recognizing in my project?


I am developing an android app using ViewModel but I am getting following error below my projectviewmodelfactory error.

below my ViewModel implementation

import android.app.Activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner

fun <T : ViewModel> Activity.obtainViewModel(viewModelClass: Class<T>): T {
    val todoRepository = (this.application as TodoApplication).todoRepository
    return ViewModelProvider(this as ViewModelStoreOwner, ViewModelFactory(todoRepository)).get(
        viewModelClass
    )

}

I want to know where I am causing an error.

below what I have tried

import android.app.Activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner

fun <T : ViewModel> Activity.obtainViewModel(viewModelClass: Class<T>): T {
    val todoRepository = (this.application as TodoApplication).todoRepository
    return ViewModelProvider(this as ViewModelStoreOwner, ViewModelProvider.Factory.get(todoRepository,
        viewModelClass
    ))

}

and getting following error Type mismatch: inferred type is ViewModelProvider but T was expected


Solution

  • If you look to the documentation ViewModelProvider constructor takes two parameters. The second one is ViewModelProvider.Factory. Replace ViewModelFactory(todoRepository) with an instance of ViewModelProvider.Factory

    fun <T : ViewModel> AppCompatActivity.obtainViewModel(viewModelClass: Class<T>): T {
            return ViewModelProvider(this).get(viewModelClass)
        }