0

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

user924
  • 8,146
  • 7
  • 57
  • 139

1 Answers1

0

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.

Tip for Android apps! 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.

Taken from: https://medium.com/androiddevelopers/things-to-know-about-flows-sharein-and-statein-operators-20e6ccb2bc74

Gilles Braun
  • 119
  • 1
  • 6