问题描述
问题是,使用LiveData是否会产生一些开销以及多少开销(无法从Doc中找到),还是可以忽略开销?
不要以为这是关于观点的问题,但确实想知道在以下情况下使用LiveData可能带来多大的麻烦(或多少开销),尤其是UI一次获取数据的一种(并且可能有多种此类UI)。
TL; DR 下面是用例,它从远程获取数据并将其发布到liveData。但是之后,这个liveData似乎在内存中什么也没做,听起来像是浪费(如果愿意,则泄漏)。并与使用协程进行比较。
用例是将有多个ui /片段(类似于集合的视图分页器,并且一些单独的片段堆叠在后堆栈中)。 每个片段都通过uuid显示数据(数据是通过一次网络调用获取的。)
一直在使用LiveData传递从存储库中获取的数据。
但是,有人质疑LiveData仅通过网络获取会为“一次”带来一些开销。也就是说,将数据发布到liveData中并由观察者获取后,附加的liveData会浪费掉内存。
问题:使用LiveData会产生多少开销?
并且可以很容易地更改为使用协程,这会比使用LiveData更好吗?
这里有一些简化的代码可以展示这个想法。 每个片段的viewModel(因此片段上有一个liveData):
class MyViewModel() : ViewModel() {
// for liveData approach:
private val liveData = MutableLiveData<Data>()
fun fetchLiveData(uuid: String): LiveData<Data> {
viewModelScope.launch {
val data = repository.getDataByUUID(uuid)
liveData.postValue(data)
}
return liveData
}
// for coroutines approach
private var fetchedData: Data? = null
suspend fun fetchData(uuid: String): Data {
withContext(Dispatchers.IO) {
fetchedData = repository.getDataByUUID(uuid) // note: the repository.getDataByUUID() is a suspend function wraps call from retrofit built with coroutines
}
// will suspend until fetchedData is coming back
return fetchedData!!
}
}
一个人在片段中使用liveData:
@Synchronized
fun observeDataByUUID(uuid: String) {
viewModel?.let {
val liveData = it.fetchLiveData(uuid)
liveData?.observe(viewLifecycleOwner,Observer {
// do ui display with the data
})
}
}
这是使用协程的:
val scope = CoroutineScope(
Job() + Dispatchers.Main
)
@Synchronized
fun fetchDataByUUID(uuid: String) {
viewModel?.let {
scope.launch(Dispatchers.Main) {
val data = it.fetchData(uuid)
data?.let{
// do ui display with the data
}
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)