如何在 android 应用程序中共享 LiveData 的实例? [英] How to share an instance of LiveData in android app?
问题描述
简单用例
我正在使用 MVVM 架构和 Android 架构组件 在我的应用中.
I am using MVVM architecture and Android Architecture Components in my app.
用户登录后,我正在获取多个网络数据并希望从不同的ViewModels 附加到不同的 Activity 生命周期.
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.
我不想在我的应用中使用 Room Persistence Library.
I don't want to use Room Persistence Library in my app.
我看到了一些关于在 Activity 之间共享 ViewModel 或使用 LiveData 作为静态成员,但我认为大多数情况下我们需要在多个屏幕中访问相同的数据.
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.
推荐答案
这个想法是有一个 Singleton 存储库,在使用者(ViewModels)之间共享一个LiveData.
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
}
}
如果出于某种原因您想刷新数据,loadItem
方法可以如下所示
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.
想象一个场景,两个 Activity 之间有转换,第一个是观察 LiveData,第二个开始刷新它.
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.
这篇关于如何在 android 应用程序中共享 LiveData 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!