Simple use case
I am using MVVM architecture and Android Architecture Components in my app.
After user logs in, I am fetchi
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.