android - 类型不匹配。必需:观察员<in int!>找到:?

标签 android kotlin android-livedata android-viewmodel mutablelivedata

我想观察ViewModel中的实时数据更改,并想更改另一个实时数据,所以我正在使用Mediatorlivedata,我不知道如何在ViewModel中观察它,我遇到了编译时错误
类型不匹配。要求:找到观察员:

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"
        }
    })
}

} enter image description here

最佳答案

您不应该在viewModel上观察实时数据,尝试将其作为源添加到mediatorLiveData并直接在 View 上观察:

val mediatorLiveData: MediatorLiveData<Int> = MediatorLiveData().apply{
   addSource(estimateyearpos) { /*Do something with "integer" */}
}

甚至(如果您不需要使其可变)
val liveData = Transformations.map(estimateyearpos) { /*Do something with "integer" */}

这两个选项都将观察源实时数据并对其应用给定功能,但是您仍然需要在Activity或片段上对其进行观察以正确获取值。

关于android - 类型不匹配。必需:观察员<in int!>找到:?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60373698/

相关文章:

android - 分页库 : Saving data in the DB doesn't trigger the UI changes

android - 如何将请求参数附加到当前 Android HttpUrlConnection 调用

Android 自定义图像按钮

kotlin - 在 kotlin 中使用带有泛型类型的类型别名?

android - ActionBar 可见性的 Observable/LiveData?

android - 使用 Room 实时查询进行生命周期状态管理

android - 如何使用改造调用 asp.net webservice?

android - windowsoftinputmode=Adjustpan 在文本对齐属性居中或 center_horizo​​ntal 时无法正常工作

java - 有没有办法在 GraalVM 原生镜像中使用 kotlin.random.Random

Kotlin 让我崩溃!当我阅读代码时,它是一个函数还是一个类?