android: SharedFlow collected twice

185 Views Asked by At

I have a simple SharedFlow in my viewModel:

private val _navigationEvent = MutableSharedFlow<PreCheckoutNavigationEvent>()
val navigationEvent = _navigationEvent.shareIn(viewModelScope, SharingStarted.Lazily )

(PreCheckoutNavigationEvent is a sealed class)

it gets emitted like:

_navigationEvent.emit(/*new instance of PreCheckoutNavigationEvent*/)

and collected in a fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        collectWhenStarted(viewModel.navigationEvent) {
           navigate(it)
        }
}

protected fun <T : Any?> collectWhenStarted(
        flow: Flow<T>,
        collector: suspend (value: T) -> Unit
    ) =
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                flow.collectLatest(collector)
            }
        }

problem is navigate() get's executed twice with the same object. I use collectWhenStarted() everywhere in the app without any issue. Only this flow is giving me problems. I even tried to collect viewModel.navigationEvent.debounce(500) but it still collects two emissions

Any idea what's causing this?

1

There are 1 best solutions below

0
On BEST ANSWER

thanks to @Pawel solved by doing

protected fun <T : Any?> collectWhenStarted(
        flow: Flow<T>,
        collector: suspend (value: T) -> Unit
    ) =
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                flow.collectLatest(collector)
            }
        }