[英]Type mismatch. Required: Observer<in Int!> Found:?
I want to Observe live data change in ViewModel and want to change another live data so I am using Mediatorlivedata, I don't know how to observe it in ViewModel, I am getting the compile-time error Type mismatch.我想在 ViewModel 中观察实时数据更改并想更改另一个实时数据,所以我使用 Mediatorlivedata,我不知道如何在 ViewModel 中观察它,我收到编译时错误类型不匹配。 Required: Observer Found: ?要求:发现观察者:?
class CheckmeasureViewModel(private val repository: UserRepository) : ViewModel() {
var estimateFinancialyear: ArrayList<FinYear> = ArrayList()
var asset = arrayListOf("Select")
var estimate = arrayListOf("Select")
var appPref: AppPref
var estimateyearpos = MutableLiveData<Int>()
var mediatorLiveData: MediatorLiveData<Int> = MediatorLiveData()
init {
appPref = AppPref.getInstance()!!
estimateFinancialyear.add(FinYear(0, "Select"))
estimateFinancialyear.addAll(repository.getFinYears())
estimateyearpos.observeForever(object : Observer<in Int> {
fun onChanged(@Nullable integer: Int?) { //Do something with "integer"
}
})
}
You Shouldn't observe a live data on the viewModel, try adding it as a source to a mediatorLiveData and observing it directly on the view:您不应在 viewModel 上观察实时数据,请尝试将其作为源添加到 mediatorLiveData 并直接在视图上观察:
val mediatorLiveData: MediatorLiveData<Int> = MediatorLiveData().apply{
addSource(estimateyearpos) { /*Do something with "integer" */}
}
or even (if you don't need it to be mutable)甚至(如果你不需要它是可变的)
val liveData = Transformations.map(estimateyearpos) { /*Do something with "integer" */}
Both of this options will observe the source live data and apply the given function to it, but you still need to observe it on an Activity or a fragment to properly get the values.这两个选项都将观察源实时数据并将给定的函数应用于它,但您仍然需要在 Activity 或片段上观察它以正确获取值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.