1

I am using MVVM + LiveData + Dagger 2.27 on my app. i am trying to call 2 APIs at the same time.

 viewModel.getMyPendingUnits()
 viewModel.getMyApprovedUnits()

and I am using MediatorLiveData to combine 2 observers

val approvedUnits = MutableLiveData<Resource<ArrayList<ApprovedUnitsResponse>>>()
val pendingUnits = MutableLiveData<Resource<ArrayList<PendingUnitResponse>>>()


val approvedAndUnApprovedUnitsLiveData: MediatorLiveData<Pair<Resource<ArrayList<ApprovedUnitsResponse>>,
        Resource<ArrayList<PendingUnitResponse>>>> =
    object :
        MediatorLiveData<Pair<Resource<ArrayList<ApprovedUnitsResponse>>,
                Resource<ArrayList<PendingUnitResponse>>>>() {
        var approved: Resource<ArrayList<ApprovedUnitsResponse>>? = null
        var pending: Resource<ArrayList<PendingUnitResponse>>? = null

        init {
            addSource(approvedUnits) { approved ->

                this.approved = approved
                pending?.let {
                    value = approved to it
                }
            }
            addSource(pendingUnits) { pending ->
                this.pending = pending
                approved?.let { value = it to pending }
            }
        }

    }

and I am observing in Fragment like this :

  viewModel.approvedAndUnApprovedUnitsLiveData.observe(viewLifecycleOwner) { (pendingUnits, approvedUnits) ->
        if (pendingUnits is Loading || approvedUnits is Loading) {
            showProgressBar(binding.communityProgressBar, true)

        } else
            if (pendingUnits is Success && approvedUnits is Success) {
}

it's working fine but when moving to another fragment and press back the observer called automatically and cause list duplication so I call removeSource like this

 override fun onDestroy() {
    super.onDestroy()
    viewModel.approvedAndUnApprovedUnitsLiveData.removeSource(viewModel.approvedUnits)
    viewModel.approvedAndUnApprovedUnitsLiveData.removeSource(viewModel.pendingUnits)
}

but it's now working. so I need to remove the observer when it's done any idea?

Mohammad Sommakia
  • 1,773
  • 3
  • 15
  • 48
  • you can use Event wrapper https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 – IR42 Jan 04 '21 at 07:53
  • Nice I already tried it but with MediatorLiveData cause a problem which is : THE first API response didn't save when the second API responded so I will lose the data. – Mohammad Sommakia Jan 04 '21 at 08:10

0 Answers0