: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.