Livefront
Published in

Livefront

By Gabriel Tocu (Own work) CC BY-SA 4.0, via Wikimedia Commons

Stop Putting State In Your View Models

Application State Inside A View Model

  1. Check if there is a file to download. If so, show a download button.
  2. When the download button is clicked, start the download.
An example UI for downloading a file
Model classes returned from the DownloadApi
  1. Call DownloadApi.search() and see if the returned FileSearchResult has a file to download.
  2. If no file exists, show the empty UI.
  3. If there is a file to download, remember the file ID
  4. When the download button is clicked, pass the file ID to the DownloadApi.downloadFile() to start the download.
else {
// This will never happen.
}

A (Bad) View Model

A View Model that tries to manage state, rather than respond to it. Though this example is somewhat trivial, notice that the complexity would increase quickly if there were more service APIs or UI events involved.

Delegate State, Don’t Manage It

  1. The View Layer (suitable for transient state)
  2. The Data Layer (suitable for persistent state)
  • Is it safe to store this state as a temporary interaction for the user? Think EditText , CheckBox, or other UI elements that may need to be refreshed when the UI is recreated.
  • Is it safe to lose this state? Does it represent something that should out-live the UI, or can it be recovered easily from source when new UI is created?
Carefully consider where state should reside. Is it transient, or should it be persisted?

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store