Michael Ferguson
2 min readApr 17, 2023

--

While I agree with the intention of common mistake 1 I don't agree with the example used.

I would also further refine it to be defined as "Don't pass UI events to the view model if they do not update state." I don't think that it's necessary for the UI to concern itself with what is or isn't "business" logic. It can simply be "if there's a change that needs to be preserved as state the view model needs to be aware of it."

Your example of expanding or collapsing is clearly a state change. It won't survive config change nor will it survive state restoration from process death.

There are UI side tweaks you can do to work-around this such as using "rememberSaveable", etc but ultimately this creates two sources of truth: the view model's state and the save instance state (if you implement it).

As you mention, the role of the android view model is to hold state and to map domain data into UI state, either directly or with the use of intermediate use cases.

Rather than using the expanded or collapsed state as an example a better example I can think of would be animation states. The UI state that the view model is holding doesn't need to know the current state of an animation. (For example the current gradient background color of a given UI widget.) It is something that can be stored with "rememberSaveable" but doesn't need to be restored from process death.

I would argue it would be pretty strange, from a user's point of view, if they rotated their device, or restored it from the background after a long period of time only to see the UI back in a collapse view. I don't think that same requirement holds true for intermediate animation values.

--

--

Michael Ferguson
Michael Ferguson

Written by Michael Ferguson

Android software developer. Views and opinions expressed are my own and not that of my employer.

No responses yet