How to share an instance of LiveData in android app?

前端 未结 1 1619
再見小時候
再見小時候 2020-12-12 02:36

Simple use case

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

After user logs in, I am fetchi

相关标签:
1条回答
  • 2020-12-12 03:28

    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.

    0 讨论(0)
提交回复
热议问题