I want to use SharedFlow
instead of StateFlow
because first one doesn't require initial value
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
Updated
It seems if values are emitted before SharedFlow was started being collected then new subscribers won't receive the latest value
So I need to change shareIn(viewModelScope, SharingStarted.Eagerly)
to
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