androidandroid-fragmentsandroid-recyclerviewsynchronizedsynchronize

Synchronize the UI and data of the recyclerview in the current fragment with the UI and data of the recyclerview in the adjacent fragment


This is the 'like' feature on Facebook. I would like to synchronize these recyclerviews with these two pieces. If you click on the 'Like' button on the recyclerview in one piece, the 'Like' button on the recyclerview should change when you change to another piece.

Which method should I use? interface? service? Map Should I use this?

What method do you use to synchronize the data of two fragments?


Solution

  • You should be using ViewModel's from architecture components. https://developer.android.com/topic/libraries/architecture/.

    Basically you create a view model in the activity so that it is stored with the activity scope

    //this is the instance of the activity
    ViewModelProviders.of(this)
    

    You can then get an instance of this view model in each fragment using

    ViewModelProviders.of(getActivity())
    

    The view model can then be used like in a standard MVVM architecture.

    Each fragment should register to the lifecycle aware components that the ViewModel would provide. MutableLiveData is one such component that you could use to provide the data back to whoever is interested in the data (in this case each fragment)

    Be aware that LiveData while does a fantastic job can be limited as it stores data as a state in time. This is great, but android should be developed where it is driven by events) As an example If you have a viewmodel which sends data to the view via livedata it could trigger a dialog. When the user closes that dialog and causes a configuration change (destroys and recreates the activity) the view will receive the state of the live data at the point in time it was set which will again show the dialog. Basically each time you rotate the device it could show the dialog agian even though you've dismissed it. A hacky fix to this is to notify the viewmodel to remove the state in the livedata after the dialog is dismissed. but this creates a number of other issues including tying view state with the viewmodel

    It's a lot more flexible if the Lifecycle aware component instead sends events of when data changes. Think Rxjava that is lifecycle aware. You add the data to the RXJava component and the observable provides the data to the observer when the view is in a state to consume it (> onresume and < ondestory).

    Hopefully that gives you a starting point. Let me know if you need more details