Hello guys! I want to collect shared flow from vie...
# compose
s
Hello guys! I want to collect shared flow from viewModel, but it works only one time.
Copy code
val scope = rememberCoroutineScope()

LaunchedEffect(scope) {
        viewModel.effect.collect {
            when(it) {
               is ShowEffect1 -> //Runs first from VM and shows
               is ShowEffect2 -> //Runs after and doesn't run here
            }
        }
    }
In ViewModel:
Copy code
private val _effect = MutableSharedFlow<CharactersScreenEffect>()
val effect = _effect.asSharedFlow()
I don't want to use .asStateFlow because it need initial state.
z
What do you do in the
ShowEffect1
case?
s
It shows snackbar. If I use asStateFlow with "Idle" initial state it works perfectly
z
Can you show more code?
Also, you don’t need to use
rememberCoroutineScope
with
LaunchedEffect
s
Copy code
LaunchedEffect(scope) {
    viewModel.effect.collect { effect ->
        when (effect) {
            is CharactersScreenEffect.ShowSnackbar -> {
                snackbarState.showSnackbar(
                    message = effect.character,
                    actionLabel = "Dismiss",
                    duration = SnackbarDuration.Indefinite
                )
            }
            CharactersScreenEffect.CloseSnackbar -> {
                snackbarState.currentSnackbarData?.dismiss()
            }
        }
    }
}
Full code
Forgot about snackbar state
Copy code
val snackbarState = remember { SnackbarHostState() }
z
showSnackbar
suspends until the snackbar goes away. If that second emission comes while the snackbar is still showing, it won’t be delivered to your collector because it’s still suspended. If you wrap
snackbarState.showSnackbar
in a
launch
, i think it will fix it.
s
Thanks, but it not fixed it
z
Another thing: instead of passing
scope
to
LaunchedEffect
(which is effectively a no-op), you might want to pass
viewModel.effect
since that’s the object you’re operating on inside the effect. E.g. If, for some reason, the view model would ever return a different
effect
, you’d need to cancel collecting on the old one but not the new one.
2
s
Damn, my bad. Your suggestion fixed my problem. Thanks!
👍🏻 1