:mega: Shootout to all Android devs using MVI, MVV...
# coroutines
📣 Shootout to all Android devs using MVI, MVVM, etc with coroutines. How do you handle events that need to be processed exactly once by your views (like navigation events, etc)? That is, what approach do you use with coroutines to work around the problem explained here for LiveData: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 0️⃣ I’m avoiding this problem altogether, not using anything like
to deliver those events (comment in 🧵 what you do instead). 1️⃣ Using an
wrapper class, adapting solution in the above story to coroutines. 2️⃣ Using a [buffered or rendezvous]
for events, exposing it to the views either as
or as a
extension. 3️⃣ Some other approach (comment in 🧵).
1️⃣ 26
3️⃣ 3
0️⃣ 7
2️⃣ 27
3️⃣ or 1️⃣ depends on how critical event is. If it have to be handled even if there are no subscribers now, then 1️⃣ is only solution (for example such cases as opening another screen or dialog asyncronously), if lost event in case of there are no subscribers is fine (like direct user interaction, like click), then 3️⃣ : so it’s just exposed as PublishSubject (so subscribers receive only new events, after subscribtion)
For the SnackBar use case: The
contains a
field that our SnackBar implementation listens to via XML Data Binding, and clears upon close-button being clicked (also via XML Data Binding), or via timeout from within ViewModel. The field can be set via a coroutine that runs within ViewModel scope. For the “press back” use case: ViewModel is not used at all since ViewModel is about data to be displayed, which is not really related to events (although of course, an event can mutate the ViewModel data, but for e.g. a “go back” event, no ViewModel data per-se is mutated. The point is that events are not stored within ViewModel, it’s only side effects of events that are stored)
We're using 1️⃣, but still with LiveData. While it would be nice to use something like a StateFlow or something instead of LiveData here, We could move to StateFlow for view state, but for events, it's more difficult. as
takes an initial value.
Granted, StateFlow for one-off events is probably the wrong move anyway. We didn't give it too much thought yet, unfortunately, and just stuck with LiveData for now.
I think the fact that MutableStateFlow doesn’t have default constructor is a bit confusing. LiveData handles it by returning null from getValue() if value is not set, but at least it a bit more flexible if you don’t want emit default value
0️⃣ in imperative way, invoked from logic, android impl details hidden behind the interface, no state means no LiveData/BehaviourRelay/StateFlow, make it simple
Surely, this would work if we wanted it to “be the same” as LiveData in that regard:
Copy code
val viewEffects: StateFlow<Event<ViewEffect>?>
    get() = _viewEffects

private val _viewEffects = MutableStateFlow<Event<ViewEffect>?>(null)
But I don't feel like events should ever be
. 😛
this would work if we wanted it to “be the same” as LiveData in that regard
LiveData doesn’t emit null if you subscribe without default value, so it’s not the same, it more like:
Copy code
val viewEffects: StateFlow<Event<ViewEffect>>
    get() = _viewEffects.mapNonNull()
Tho it still looks unnecessary to do with operator
0️⃣ since navigation is not an observable state.
👍🏽 4
🚫 1
@flosch It’s not an “observable state” but you can expose navigation events as a stream of events, exactly what Flow does, it’s very powerful, and also the only proper way to implement navigation with MVVM with detachable VM, on Android at least, but not only, when you need current screen context to do navigation, but you cannot hold reference on it
For the snackbar case, you're supposed to use it in the manual show/hide mode and then you can use a LiveEvent (which really should be named LiveState). For click a button and go to a different frag/activity, I've usually hooked them up using flowbindings like you'd do with rxbindings.
2️⃣ , as a new class
, implementing
by a Rendezvous Channel's
. It has two methods/props:
CoroutineScope.value: T
(only as a setter) and
suspend fun postValue(v: T)
., both sending the providied value to the Channel.
I’m also using a RendezvousChannel; not sure whether that should count as 2️⃣ or 3️⃣
Pick 2️⃣ if you use any kind of channel
We associate an ID with the event (eg a random UUID or monotonically increasing int), store the event in the UI's view model, and "fire" the event by changing the ID. The consuming view is expected to track this ID over time and detect when it changes. This is rare though, our navigation is state-based, not event-based, and we try to push as much code as possible to be state-based, so the toast/snackbar example is I think only case, or at least the main case, where we need this.
Collect the
of events and stop collecting when the
is not in the correct state for handing the event.
Fwiw the reason this article exists is because
is a state type, not an event stream type. 1️⃣ is a hack to work around this without sorting out the difference between events and state in the app, which has been pretty harmful to the understanding of the whole space for a lot of people since it was written.
💯 1
@gildor You said: expose navigation events as a stream of events - Can you show some article or project implementing it? I've never used this approach 🙂
@henrikhorbovyi You may check an article mentioned by Roman in his message, it show example of this approach. Essentially when navigation events exposed as stream of events when view subscribes on those events and dispatch them
👍 1
Event wrapper with livedata is what I see in majority of code bases... channels i would think is more tricky based on the different lifecycles
I was confused about this discursion before 😄 But now I got the point. I agree @rkeazor
@Adam Powell Why can't we pull that dang article down?
I think I've been having that discussion with Jose on and off for two years now 🙂 when it was posted Flow wasn't in the picture as a stable API and the alternative to recommend would have been RxJava, and even now the wider Android developer community is still wrapping their heads around coroutines conceptually. It's a lot to ask people to learn, and that post offered a quick band-aid instead.
A quick fix for a war time wound left un-attended can lead to sepsis. 😁
Re: Roman's original question I use two channels between view<->viewmodel: one for state and one for ephemeral events. ephemeral events: navigation, toasts, alerts, transitions https://github.com/kaushikgopal/movies-usf-android -- is a good example.