The Internals of ViewModel and Surviving Configuration Changes

Milind Amrutkar
4 min readJun 27, 2023

--

Introduction

In the Android world, the ‘ViewModel’ has become a vital component, especially when adopting the MVVM(Model-View-ViewModel) architecture. The ‘ViewModel’ class is designed to hold and manage UI-related data in a lifecycle-conscious way, surviving configuration changes like screen rotations. But how does it achieve that? Let’s peel back the layers and see what’s going on under the hood.

ViewModel: The Basics

Before diving into the internals, let’s revisit what a ‘ViewModel’ is. A ‘ViewModel’ is an architectural component that is used to hold and manage data for views (such as Activities and Fragments) in a way that is conscious of lifecycle events. This helps to separate the responsibilities of data handling and view displaying, leading to more manageable and testable code.

How ViewModel Works Internally

When we create a ‘ViewModel’ instance, we usually use ‘ViewModelProvider’, like so:

val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
Photo by liam siegel on Unsplash

This ‘ViewModelProvider’ uses a ‘ViewModelStore’ to retain ‘ViewModel’ instances. Let’s have a look at a simplified ‘ViewModelProvider’:

class ViewModelProvider (
private val store: ViewModelStore,
private val factory: Factory
) {
fun <T: ViewModel> get(modelClass: Class<T>): T {
var viewModel = store.get(modelClass.name)

if(viewModel == null) {
viewModel = factory.create(modelClass)
store.put(modelClass.name, viewModel)
}

return viewModel as T
}

interface Factory {
fun <T: ViewModel> create(modelClass: Class<T>): T
}
}

In the ‘get’ method, ‘ViewModelProvider’ first tries to get an existing ‘ViewModel’ from the ‘ViewModelStore’ using the class name as the key. If a ‘ViewModel’ with this key doesn’t exist, it creates a new one using the provided ‘Factory’, then stores it in the ‘ViewModelStore’.

The ‘ViewModelStore’ is a simple container that holds ‘ViewModels’. It’s associated with the lifecycle of an ‘Activity’ or ‘Fragment’ and is retained during configuration changes.

class ViewModelStore {
private val map: HashMap<String, ViewModel> = HashMap()

internal fun put(key: String, viewModel: ViewModel) {
val oldViewModel = map.put(key, viewModel)
oldViewModel?.onCleared()
}

internal fun get(key: String): ViewModel? {
return map[key]
}
}

When an ‘Activity’ or ‘Fragment’ is created, it will either create a new ‘ViewModelStore’ or retrieve the one that was created during a previous configuration.

How ViewModel Survives Configuration Changes

‘ViewModel’ survives configuration changes due to the way ‘ViewModelStore’ is kept alive by the ‘Activity’ or ‘Fragment’.

When an ‘Activity’ is recreated (e.g., due to a configuration change like screen rotation), the system keeps the ‘ViewModelStore’ alive and passes it to the new ‘Activity’ instance. This way, when the new ‘Activity’ instance asks for a ‘ViewModel’ of a particular class, the ‘ViewModelProvider’ finds the existing instance in the ‘ViewModelStore’ and returns it, ensuring that the ‘ViewModel’ survives the configuration change.

However, when the ‘Activity’ is finishing (i.e., it’s being destroyed permanently, not due to a configuration change), the ‘ViewModelStore’ is also cleared, and the ‘onCleared’ method is called on all ‘ViewModels’ in the store.

Conclusion

Understanding the inner workings of ‘ViewModel’ can help us better grasp the lifecycle of Android components, making us more effective Android Developers. Even though much of this happens “magically” behind the scenes, knowing what’s going on can help you debug issues and design your apps more effectively. Happy Coding!

Read more:

If you found this article enlightening and valuable, don’t hesitate to give it some claps 👏 — it’s a great way to show your support! Please share it with your peers to spread the knowledge. And if you want to keep up with my latest insights, be sure to follow my Medium profile. Your engagement truly makes a difference and helps me create more content you love. Thank you for reading!

Explore these recommended books to enhance your Android development skills. Each one covers various aspects of Android programming, from basics to advanced topics:

  1. Head First Android Development — Ideal for beginners looking for a visually engaging way to start Android programming. Buy it here 👈
  2. Modern Android 13 Development Cookbook — Filled with practical recipes for the latest Android versions. Buy it here 👈
  3. Android Application Development — Black Book — A comprehensive guide covering detailed development strategies. Buy it here 👈
  4. Clean Architecture for Android — Learn to write maintainable and scalable code. Buy it here 👈
  5. Programming Android with Kotlin — Dive into Android programming using Kotlin, a modern programming language. Buy it here 👈
  6. Androids: The Team That Built the Android Operating System — Gain insights into the history and people behind Android. Buy it here 👈

These resources are great for expanding your knowledge and skills in Android development. Share them with your peers and explore these titles to advance your coding capabilities.

--

--

Milind Amrutkar

Android developer @ Priceline & YouTuber. Passionate about tech, reading, writing. Join me on YouTube @MilindAmrutkarM-A & Medium.