How to correctly use flow from ViewModel to open `...
# compose-android
r
How to correctly use flow from ViewModel to open
ModalBottomSheet
? I get multiple bottom sheets opened although the flow is triggered once. Also, if I put app on the background and re-open the app then extra bottom sheet is opened. blob nervous
XYZ - I need to show modal bottom sheet when I receive expected response from backend.
j
The current recommendation (as far as I know) is to model the event as state and reset the state after you successfully triggered the modal sheet. Will show you an example in a sec:
Sample.kt.cpp
k
@Rihards not having seen your code, I’m just making a guess here that you may be using
StateFlow
. You may be able to use
SharedFlow
with 0 replay, instead. Your view starts listening and collects the publish, indicating it should open the sheet, but now when you have something like a configuration change (and you’ve `remember`ed that your sheet is open), it starts collecting again, but because replay is 0 it collects nothing.
I have found
SharedFlow
to be similarly helpful when I want to fire off a signal to show a snackbar and don’t want to show it more than once (and also don’t want to have to “signal back” that the message has been consumed and can be cleared).
r
Thank You both for the help! I previously tried both SharedFlow and StateFlow, but didn’t try to use replay as 0. Will check how it goes with all this information 🙌
👍 1
j
and also don’t want to have to “signal back” that the message has been consumed and can be cleared
the problem there is, that if the consumer is not ready (for example during a config change) the event could get lost.
gratitude thank you 1
k
Here’s what I got to work:
Copy code
private val _snackbarMessage = MutableSharedFlow<String>(0,1, BufferOverflow.DROP_OLDEST)
    val snackbarMessage = _snackbarMessage.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0)
The confusing/key part was being sure to pass in extraBufferCapacity as 1.
gratitude thank you 1
@Jonas fair point. I suppose it may come down to how mission critical it is for this thing to happen (in my case, the off chance that an error snackbar doesn’t get shown feels like an acceptable risk). So yeah,
SharedFlow
may not always be the best option if it’s super important.
j
agree 🙂 I like to do it always the same way but it’s for sure some overhead.