ifTrueOrDefault

fun <T : Any, B : Boolean?> LiveData<B>.ifTrueOrDefault(default: T, block: () -> LiveData<T>): LiveData<T>

Executes and switchMaps to block if this has a true value. If this is false or null, it returns LiveData with value default. This can be used instead of ifTrue when the default value should be something other than null. Note that this requires a non-null value for T in order for Kotlin's compiler to properly spot missing null-checks.

This can be used to replace:

myLiveData.switchMap {
if (it == true) {
myNewLiveData
} else {
MutableLiveData(default)
}
}.distinctUntilChanged()

with a more concise syntax:

myLiveData.ifTrueOrDefault(default) { myNewLiveData }