Home > Software engineering >  convert boolean value into MutableLiveData<Boolean>
convert boolean value into MutableLiveData<Boolean>

Time:09-18

var booleanresult : MutableLiveData<Boolean>? = null

fun checksubcat() = viewModelScope.launch(Dispatchers.IO) {
    val trueorfalse : Boolean = productsDao.getSubCatId(subcat_id)
    booleanresult?.value = trueorfalse
    Log.e("update","view model" booleanresult?.value.toString())
}

Log value for trueorfalse variable :

2022-09-18 06:58:32.305 11820-11849/com.store.pasumainew E/update: trueorfalse : false

I got log value of null for booleanresult:

2022-09-18 06:58:32.305 11820-11849/com.store.pasumainew E/update: booleanresult : null

I need booleanresult as MutableLiveData ..how to set trueorfalse value to MutableLiveData

CodePudding user response:

Your LiveData property should not be nullable and should never be null. And it should not even be a var because there should never be a reason to create a new one instead of setting the value of the existing instance.

Declare it as non-nullable (no question mark), give it an initial value, and make it a val.

val booleanResult = MutableLiveData<Boolean>()

You also can’t directly set the value using Dispatchers.IO. Convention is to usually not change the dispatcher for your launch call but only use it for specific sections of your coroutine using withContext. But if for some reason you didn’t follow the convention, then you need to use postValue() instead of value =, since that is only allowed to be done on the main thread.

  • Related