Search code examples
androidandroid-architecture-componentsandroid-livedataandroid-jetpackandroid-viewmodel

How to share an instance of LiveData in android app?


Simple use case

I am using MVVM architecture and Android Architecture Components in my app.

After user logs in, I am fetching multiple network data and want to have access to it from different ViewModels attached to different Activities lifecycle.

I don't want to use Room Persistence Library in my app.

I have seen some question about sharing a ViewModel between Activities or using a LiveData as static member, but I think most of the cases we need to access the same data in multiple screens.

I want to share a solution, but if there is better one or there is an issue with this, please post your thoughts.


Solution

  • The idea is to have a Singleton Repository, which shares a LiveData between consumers (ViewModels).

    class SharedLiveDataRepository(val dataSource: MyDataSource) {
    
        // This LiveData is shared across consumers
        private val result = MutableLiveData<Long>()
    
        fun loadData(): LiveData<Long> {
            if (result.value == null) {
                result.value = dataSource.getData()
            }
            return result
        }
    
    }
    

    If for some reason you would like to refresh the data, the loadItem method can look like this

      fun loadData(refresh: Boolean = false): LiveData<Long> {
            if (refresh == true) {
                result.value = null
            } 
            if (result.value == null) {
                result.value = dataSource.getData()
            }
            return result
        }
    

    Please Note: For refreshing the data it is possible to see a glitch.

    Imagine a scenario when there is transition between two activities and first one is observing the LiveData and the second one starting refreshing it.

    I think the solution for the above issue is to do the refresh in first activity and then navigate to the next one.