简体   繁体   English

SharedFlow 不会在片段(收集)处向订阅者发出值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM