How to share an instance of LiveData in android app?

南楼画角 提交于 2019-12-17 21:16:34

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/56521969/how-to-share-an-instance-of-livedata-in-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!