android – Type mismatch. Required: Observer<in Int!> Found:?-ThrowExceptions

Exception or error:

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

    estimateyearpos.observeForever(object : Observer<in Int> {
        fun onChanged(@Nullable integer: Int?) { //Do something with "integer"

}enter image description here

How to solve:

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:

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 = { /*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.

Leave a Reply

Your email address will not be published. Required fields are marked *