首页 > 解决方案 > LiveData如何获取副本数?

问题描述

我在 ViewPager 中有一个包含多个片段的应用程序。有 RecyclerViews 的数据可能在其他片段中重复。所以我决定在一个存储库中为每个单元使用一个 MutableLiveData(使用唯一的密钥),无需额外的副本

livedata中的数据如下:

class Data {
    var id = 0
    var type = 0
    var name = ""
    var onlineStatus = OnlineStatus.GroupOrWithout
    var icon: Bitmap: ?= null
}

map[data.id + data.type] = Data()

// when we need this data
fun getData(id: Int, type: Int) : MutableLiveData<Data>? {
    val res = map[id + type]
    if(res != null) {
        return res
    }
    // or create new one if this fist time when we need it
    ....
}

但现在我意识到,使用 LiveData 的传统方法仅限于片段的生命周期。优点是在fragment被销毁后销毁未使用的数据。但是这种方式对我来说看起来更复杂,因为另一个片段中的事件可能会丢失,然后即使是相同元素,我也会有不同步的数据。

所以我在想,如果 MutableLiveData 没有来自片段的引用,我可以手动操作和销毁它吗?

可能在 android 中是来自 c++ 的 shared_ptr 的类似物?我真的很喜欢当前的架构,但我不知道如何清理未使用的更多 LiveData

标签: androidandroid-livedatamutablelivedata

解决方案


推荐阅读