Search code examples
androidandroid-livedataconcept

android, observer two different mutable live data at once


I want to observe two different mutable live data at once. is there any way I can achieve this in android, both data are lies with different ViewModel also.


Solution

  • You can use MediatorLiveData to combine two live data sources into one. Here's a quick example that combines livedata1 and livedata2 from two separate view models into a MediatorLiveData, which emits a data class that contains the result from livedata1 and livedata2. Anytime livedata1 or livedata2 changes, the mediator will be triggered

    data class CombinedResult(val firstData: DataType1, val secondData: DataType2)
    
    private fun createLiveDataMediator() : LiveData<CombinedResult> {
    
        val result = MediatorLiveData<CombinedResult>()
    
        val firstLiveData = myViewModel.getLiveData1()
        val secondLiveData = mySecondViewModel.getLiveData2()
    
        result.addSource(firstLiveData) {
            result.value = CombinedResult(firstLiveData.value, secondLiveData.value)
        }
        result.addSource(secondLiveData) {
            result.value = CombinedResult(firstLiveData.value, secondLiveData.value)
        }
    
        return result
    }