emen
emen

Reputation: 6318

How do I update new data in ViewPager2 fragments?

I have a Fragment that contains:

What I want to achieve is when user click on the custom view, it will update the data in the RecyclerView.

In my case, when a user unselects an item in the custom view, it will also unselect what is inside the RecyclerView items.

I'm not sure how to do this with a listener that goes back down to the RecyclerView's Adapter level. Anyone have any idea on how to achieve this?

Below is a simple diagram I drew to illustrate this.

enter image description here


Update: I've solved this issue by using notifyDataSetChanged() across all the fragments in the ViewPager2. A bit tedious to communicate through all code spaghetti, but it works. If anyone come across similar issue, you can either follow my method or look at the answer below. Either way works, depends on your project structure.

Upvotes: 3

Views: 1549

Answers (2)

Daniyal Javaid
Daniyal Javaid

Reputation: 1636

You can communicate using:

  1. SharedViewModels: Both Fragments use same SharedViewModel, 1 will update the Observable(LiveData/Flow) in viewModel and another fragment will observe the changes for that Observable(LiveData/Flow)

  2. Flows/LiveData: exposed from any Repository or UseCase layer Similar to SharedViewModels, but your Observable(LiveData/Flow) will be in either Repository or UseCase and your both viewModels of both fragments will be injecting same Repository/UseCase.

  3. RoomDB: Store that data in RoomDB and return Flow/LiveData from Room DAO. And observe this flow in your fragment. Whenever the DB changes, your fragment will be notified with updated data.

Upvotes: 3

Devrim Catak
Devrim Catak

Reputation: 66

you can use BroadcastReceiver for this. In cases you want to trigger, when you broadcast, the relevant code will be triggered on the Fragment you want to capture the broadcast.

You can also use the EventBus library. Both methods will work, but the EventBus manufacturer claims that they are more performant than BroadcastReceiver.

Upvotes: 1

Related Questions