How to make a combination of two live data objects properly

  android, android-livedata, kotlin

I have two LiveData objects of the same type and I want to do the same calculations on the output. Something like a merge operator in Rx how can I achieve this. currently I’m doing it like so:

class VM : ViewModel() {
    val input1LiveData = MutableLiveData<Int>()
    val input2LiveData = MutableLiveData<Int>()
    val squareLiveData = MutableLiveData<Int>()
}

class MyFragment : Fragment() {
    private void fillSquare(input: Int){
        viewmodel.squareLiveData.value = input * input
    }
    override onViewCreated(){
        viewmodel.input1LiveData.observe(viewLifecycleOwner){
            fillSquare(it * it)
        }
        viewmodel.input2LiveData.observe(viewLifecycleOwner){
            fillSquare(it * it)
        }
    }
}

Which I guess is a bad approach

Source: Android Questions

LEAVE A COMMENT