:mega: Shootout to all Android devs using MVI, MVV...
# coroutines
e
📣 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
Rx/Channel/Flow/LiveData
to deliver those events (comment in 🧵 what you do instead). 1️⃣ Using an
Event
wrapper class, adapting solution in the above story to coroutines. 2️⃣ Using a [buffered or rendezvous]
Channel
for events, exposing it to the views either as
Channel
or as a
Flow
via
receiveAsFlow()
extension. 3️⃣ Some other approach (comment in 🧵).
1️⃣ 26
3️⃣ 3
0️⃣ 7
2️⃣ 27
g
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)
m
For the SnackBar use case: The
ViewModel
contains a
LiveData<MessageToShow>
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)
s
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
MutableStateFlow()
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.
g
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
p
0️⃣ in imperative way, invoked from logic, android impl details hidden behind the interface, no state means no LiveData/BehaviourRelay/StateFlow, make it simple
3
s
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
null
. 😛
g
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
f
0️⃣ since navigation is not an observable state.
👍🏽 4
🚫 1
g
@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
k
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.
s
2️⃣ , as a new class
EventFlow
, implementing
Flow
by a Rendezvous Channel's
receiveAsFlow()
. 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.
d
I’m also using a RendezvousChannel; not sure whether that should count as 2️⃣ or 3️⃣
e
Pick 2️⃣ if you use any kind of channel
z
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.
d
Collect the
Flow
of events and stop collecting when the
LifecycleOwner
is not in the correct state for handing the event.
a
Fwiw the reason this article exists is because
LiveData
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
h
@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 🙂
g
@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
r
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
h
I was confused about this discursion before 😄 But now I got the point. I agree @rkeazor
d
@Adam Powell Why can't we pull that dang article down?
a
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.
d
A quick fix for a war time wound left un-attended can lead to sepsis. 😁
b
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.