One Off the Slack: ViewModels... Going, Going, Gone?

Brady Aiello asked:

Since Composables will eventually replace Fragments, I was wondering if we’ll be able to scope ViewModels to Composables, or Composable destinations within Compose Navigation? Keeping lots of ViewModels all scoped to a single Activity, or keeping one god-ViewModel would both hold data for every page in memory concurrently, and that seems like a bad idea.

Google’s Ian Lake eventually chimed in with a definitive answer:

Navigation already scopes ViewModels to individual destinations and had since it’s first alpha

Along the way, though, Google’s Adam Powell pointed out a few key ideas. One is that the old activity destroy-and-recreate cycle is perhaps unnecessary:

if you’re using all-compose, there’s no reason to leave activity recreation for configuration changes enabled since compose knows how to handle them at a much finer granularity

Personally, while I think that this is a fine objective, I suspect that it may not turn out as well as Adam would like. If nothing else, it will require developers to pay very close attention to new types of configuration changes, as the android:configChanges attribute is a change blacklist. Any new type will trigger a configuration change, unless developers add it to android:configChanges. This will be easy to miss with the typical glacial pace of Android upgrades. Perhaps this can be handled via Lint.

Adam goes onto say:

which then means the arch components ViewModel superclass doesn’t serve much purpose; any old object you remember {} persists as normal

we have the savedInstanceState APIs in compose already for saving across process restarts, and that doesn’t experience the same ViewModel scoping questions

In other words, viewmodels may not go away, but ViewModel might not be the base class for them. We still are going to want something in that role, for testability if nothing else. But we might be able to avoid some of the ViewModel quirks.

Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!