Using MediatorLiveData to return if two LiveDatas are true

109 Views Asked by At

Say I have two LiveData events, eventPlayerChose and eventOppChose, and I want to use MediatorLiveData eventRoundFinish to signal that both LiveDatas are true. Is this the best way to do so or is there a cleaner solution?

private val _eventPlayerChose = MutableLiveData<Boolean>()
val eventPlayerChose: LiveData<Boolean>
    get() = _eventPlayerChose

private val _eventOppChose = MutableLiveData<Boolean>()
val eventOppChose: LiveData<Boolean>
    get() = _eventOppChose

// a round finishes when both players choose
private val _eventRoundFinish = MediatorLiveData<Boolean>().apply {
    var playerChose = false
    var oppChose = false
    value = false
    addSource(eventPlayerChose) { hasChosen ->
        playerChose = hasChosen
        value = playerChose && oppChose
    }
    addSource(eventOppChose) { hasChosen ->
        oppChose = hasChosen
        value = playerChose && oppChose
    }
}
val eventRoundFinish: LiveData<Boolean>
    get() = _eventRoundFinish
0

There are 0 best solutions below