[英]SharedFlow won't emit value to subscriber at fragment (collect)
I want to use SharedFlow
instead of StateFlow
because first one doesn't require initial value我想使用
SharedFlow
而不是StateFlow
因为第一个不需要初始值
ViewModel :视图模型:
val photosPaginData = photoRepository.getPhotosPagingData() // Flow<PagingData<Photo>>
.cachedIn(viewModelScope)
.shareIn(viewModelScope, SharingStarted.Eagerly)
Fragment :片段:
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.photosPaginData.collect { pagingData ->
photosAdapter.submitData(pagingData) // no calls here...
}
}
I'm only trying to use it for the first time so mb I don't fully understand how it works.我只是第一次尝试使用它,所以我不完全理解它是如何工作的。
It works fine if I replace shareIn
with stateIn
and set null
as initial value (third parameter) but then in collect
callback I need to check if it's not null
before submit PagingData
to the adapter如果我用
null
替换shareIn
并将stateIn
设置为初始值(第三个参数),它工作正常,但是在collect
回调中我需要在将PagingData
提交给适配器之前检查它是否不是null
Updated更新
It seems if values are emitted before SharedFlow was started being collected then new subscribers won't receive the latest value似乎如果在开始收集 SharedFlow 之前发出值,那么新订阅者将不会收到最新值
So I need to change shareIn(viewModelScope, SharingStarted.Eagerly)
to所以我需要将
shareIn(viewModelScope, SharingStarted.Eagerly)
更改为
shareIn(viewModelScope, SharingStarted.WhileSubscribed())
or to或者
shareIn(viewModelScope, SharingStarted.Eagerly, replay = 1)
to make it work让它发挥作用
But which one is better?但是哪一个更好呢? I just need to keep the same single instance of
PagingData
我只需要保留同一个
PagingData
实例
I recommend against using SharingStarted.Eagerly
, as it will never cancel the upstream flow, even if the observing activity/fragment is not observing any more.我建议不要使用
SharingStarted.Eagerly
,因为它永远不会取消上游流,即使观察活动/片段不再观察。
Tip for Android apps.
Android 应用程序的提示。 You can use WhileSubscribed(5000) most of the time to keep the upstream flow active for 5 seconds more after the disappearance of the last collector.
您可以在大多数情况下使用 WhileSubscribed(5000) 在最后一个收集器消失后保持上游流活动 5 秒以上。
Taken from: https://medium.com/androiddevelopers/things-to-know-about-flows-sharein-and-statein-operators-20e6ccb2bc74取自: https://medium.com/androiddevelopers/things-to-know-about-flows-sharein-and-statein-operators-20e6ccb2bc74
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.