简体   繁体   中英

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.
}

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)

you can do something like this

fun switchCheckBox() = _displayCheckBox.value?.let { _displayCheckBox.postValue(!it) }

postValue will trigger the observer for displayCheckBox

I am not a fan of using a .let in this scenario because that would preserve the null value of the LiveData which is obviously something you are intending to avoid. I would use the following:

fun toggleDisplayCheckBox() {
    _displayCheckBox.run { value = value == false }
}

This adheres to the following Boolean? mapping:

When the value is...
    true -> false
    false -> true
    null -> false

In the case where you want the value to be set to true instead of false when it is null, the following could be used instead:

fun toggleDisplayCheckBox() {
    _displayCheckBox.run { value = value != true }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM