Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set value of MutableLiveData<Boolean>() as adverse in Kotlin?

_displayCheckBox is a MutableLiveData<Boolean>, I hope to set it as adverse.

But It seems that _displayCheckBox.value = !_displayCheckBox.value!! can't work well, how can I fix it?

Code A

private val _displayCheckBox = MutableLiveData<Boolean>(true)
val displayCheckBox : LiveData<Boolean> = _displayCheckBox

fun switchCheckBox(){
    _displayCheckBox.value =  !_displayCheckBox.value!!   //It seems that it can't work well.
}
like image 304
HelloCW Avatar asked Sep 11 '20 00:09

HelloCW


People also ask

What is the difference between LiveData and MutableLiveData?

By using LiveData we can only observe the data and cannot set the data. MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods (the former being thread-safe) so that we can dispatch values to any live or active observers.

What is MutableLiveData Kotlin?

Live data or Mutable Live Data is an observable data holder class. We need this class because it makes it easier to handle the data inside View Model because it's aware of Android Lifecycles such as app components, activities, fragments, and services. The data will always update and aware of its Lifecycles.

Is Boolean a data type in Kotlin?

For this, Kotlin has a Boolean data type, which can take the values true or false .

How do I initialize kotlin LiveData?

“how to initialize livedata kotlin” Code Answerval liveData = MutableLiveData<String>(). default("Initial value!")


2 Answers

If you wrap the set value with a scope function such as let, you'd be able to negate the value only if it is not null, otherwise, the negation would be ignored.

fun switchCheckBox() {
    _displayCheckBox.value?.let {
        _displayCheckBox.value = !it
    }
}
like image 85
aminography Avatar answered Oct 29 '22 01:10

aminography


This will transform the live data inverting the liveData value, it will observe _displayCheckBox and change its appling the {!it} operation to its value:

private val _displayCheckBox = MutableLiveData<Boolean>(true)
val displayCheckBox = Transformations.map(_displayCheckBox) { !it }

Note that you have to observe the value to trigger the updates:

SomeActivity.kt

displayCheckBox.observe(this, Observer {value -> 
    // Do something with the value 
})

Here is the docs: https://developer.android.com/reference/androidx/lifecycle/Transformations#map(androidx.lifecycle.LiveData%3CX%3E,%20androidx.arch.core.util.Function%3CX,%20Y%3E)

like image 20
Luciano Ferruzzi Avatar answered Oct 29 '22 01:10

Luciano Ferruzzi