Whenever I am trying to delegate my viewmodel
using the delegated property
in my Fragments
val viewModel:NewsViewModel by activityViewModels<> { }
This is the error
I would receive.
Property delegate must have a 'getValue(BreakingNews, KProperty*>)' method. None of the following functions are suitable.
Lazy<NewsViewModel>.getValue(Any?, KProperty<*>)
where T = NewsViewModel for inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property:
KProperty<*>): T defined in kotlin
However, instantiating the viewmodel
instance in the MainActivity
this way, seems fine
val viewmodelFactory = ViewModelProviderFactory(dataRepo)
viewModel = ViewModelProvider(this,viewmodelFactory).get(NewsViewModel::class.java)
I assumed at first it may be due to the viewmodelFactory
which is as follows.
class ViewModelProviderFactory(val Repo:NewsRepository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>,extras: CreationExtras): T {
return NewsViewModel(Repo) as T
}
}
The code below are the properties in my ViewModel
, This is odd as I have cross-referred from multiple sources including the official `docs.
var breakingNews: MutableLiveData<Resource<ArticleList>> = MutableLiveData()
var breakingNewsPage = 1
var breakingNewsResponse: ArticleList? = null
var searchNews: MutableLiveData<Resource<ArticleList>> = MutableLiveData()
var searchNewsPage = 1
var searchNewsResponse: ArticleList? = null
var savedNumerics = 0
var _status = MutableLiveData<String>()
....
}
CodePudding user response:
Usually, you want just val viewModel:NewsViewModel by activityViewModels()
.
In your case, with val viewModel:NewsViewModel by activityViewModels<> { }
, you skipped two things.
First, you are attempting to provide a value for the extrasProducer
parameter to the activityViewModels()
function. However, that lambda expression needs to evaluate to a CreationExtras
object, and yours evaluates to Unit
.
Second, you failed to provide a type. AFAIK, <>
is not going to be valid syntax here. Either leave the <>
off (and the compiler should infer the type from the property type) or fully qualify it as <NewsViewModel>
. I think this is the cause of your specific syntax error, but even if you fix this, you should then run into a problem with your empty lambda expression.