_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.
}
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.
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.
For this, Kotlin has a Boolean data type, which can take the values true or false .
“how to initialize livedata kotlin” Code Answerval liveData = MutableLiveData<String>(). default("Initial value!")
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
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With