RecyclerView Adapter change the list when updating different observable

Viewed 563

I'm developing a android application using Room library and Lifecycles. currently I have two List Livedata and having one Observable stream by using MediatorLivedata and One recyclerview adapter. The app has two tab in tablayout, Every tab has own list same datatype but different values. E.g Livedata1 = Tab1 , Livedata2 = Tab2

When user select tab2 the list change to tab2 and go back to Tab1 the list change to tab1 and update the current item in the tab1, the list change to tab2 even i don't change the tab.

How can I fix that issue?

I've already tried to remove the DataSource in MediatorLivedata when user change tab but issue still same

//ViewModel

private var getAllListOfOrders = MediatorLiveData<List<OrderEntities>>()

init {
    getAllListOfOrders.addSource(getAllListPreparingOrders){ getAllListOfOrders.value = it }
}


fun getAllOrders() : LiveData<List<OrderEntities>>{
    return getAllListOfOrders
}

fun isForPickUp(tabName: String){
    if (!tabName.equals("For Preparing", true)){
        getAllListOfOrders.addSource(getAllListPickUpOrders){
            getAllListOfOrders.value = it
            getAllListOfOrders.removeSource(getAllListPickUpOrders)}

    }else{
        getAllListOfOrders.addSource(getAllListPreparingOrders){
            getAllListOfOrders.removeSource(getAllListPickUpOrders)
            getAllListOfOrders.value = it }
    }
}

//Activity

orderViewModel.getAllOrders().observe(this, Observer {
        adapter.setOrderList(it as ArrayList<OrderEntities>)
    })

//RecyclerView Adapter

   fun setOrderList(orderList : ArrayList<OrderEntities>){
    this.orderList = orderList
    notifyDataSetChanged()
}

The expected result when user didn't change tab the list don't change

2 Answers

I noticed something in your code. Try replacing:

if (!tabName.equals("For Preparing", true)){
        getAllListOfOrders.addSource(getAllListPickUpOrders){
            getAllListOfOrders.value = it
            getAllListOfOrders.removeSource(getAllListPickUpOrders)}

    }

with:

if (!tabName.equals("For Preparing", true)){
        getAllListOfOrders.addSource(getAllListPickUpOrders){
            getAllListOfOrders.value = it
            getAllListOfOrders.removeSource(getAllListPreparingOrders)}

    }

because it looks like you never remove getAllListPreparingOrders as a source.

I don't know what you are aiming to design here, but, if you insist on designing with MediatorLiveData read this article: MediatorLiveData to the Rescue

Personally I think the correct design is to use 2 observers each for 1 LiveData and updating the list of one tab. As I said I don't know what is your plan so the choice is yours.

Related