Given views have shorter lifecycle than viewmodels...
# android-architecture
u
Given views have shorter lifecycle than viewmodels, how do you handle "transient" errors? If such async request is modeled into a single viewmodel State, or has its own LiveData, and UI wants to show
Toast
or error,
it will re-show the Toast after new view instance is created (after coming back from background, or on rotation), which might be confusing to the user
m
You could add a variant for logging for the state type. Instead of a simple string, make it contain a function that emits a string. When you want to log when entering a state, wrap that state in a function that returns a string, then emit the logging state. So when you pattern match on the logging state, you extract the log message by calling the function and the view model enters its actual state.
u
So basically you are reseting it to
_state.value = State.Done
after rendering it?
m
yes
s
“LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)” de Jose Alcérreca https://link.medium.com/HOAZgeFW53 Use an
Livedata<Event<T>>
with a one time consumable event 👌
m
If you really want to "design events as part of your state" as the article says, then don't use a generic type like that. Add it to your state sum like I did above. Honestly, that article reads to me like an excuse for not providing
PublishLiveData
.
🤔 1
t
I suppose the clean way would be to have the view send an event back to the viewmodel to reset the error. This would make it possible to gracefully handle the case where the error should be shown for some time before disappearing (toast) but view is killed before the time is over. If the view is killed immediately then the user might not have seen the toast. Or you could refactor a toast-like error to something that has to be dismissed manually. The other "cleanish" option is to have the viewmodel reset the state itself after a timeout decided in the viewmodel. I feel that this leaks view concerns into the viewmodel (how long should error be shown) but this is a very open question anyway when you consider stuff like animation state that we would usually store in the view due to historical reasons. Personally, I don't bother and just send a one-time event through a custom Rx relay that buffers events when nobody is subscribed. I think SingleLiveData or whatever is similar but I have done my best to ignore the existence of LiveData so far, so I couldn't tell you for sure.
u
@tiga
custom Rx relay that buffers events when nobody is subscribed.
mind sharing this?
u
nice, thanks