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?
thanks to @Pawel solved by doing