ViewModelStore Explained: An In-Depth Guide

Milind Amrutkar
4 min readJul 1, 2023

--

Photo by Fikri Rasyid on Unsplash

Introduction

Android’s ‘ViewModel’ is a cornerstone of modern app development, particularly in apps adopting the MVVM(Model-View-ViewModel) architecture. Paired with this is the ‘ViewModelStore’, an integral component that enables ‘ViewModels’ to survive configuration changes, such as screen rotations. Today, we’ll dissect the ‘ViewModelStore’, exploring its code and inner workings.

What is ViewModelStore?

In essence, the ‘ViewModelStore’ is a container that holds ‘ViewModels’. It enables ‘ViewModels’ to remain in memory across the lifecycle of an Activity or Fragment, even through configuration changes. This is a key feature that sets ‘ViewModels’ apart from other components like Activities and Fragments that are destroyed and recreated on configuration changes.

ViewModelStore Code Explained

Here’s a simplified version of its implementation:

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]
}

fun clear() {
for (viewModel in map.values) {
viewModel.onCleared()
}
map.clear()
}
}

Now, let’s break down this code line by line:

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

The ‘ViewModelStore’ maintains a ‘HashMap’ where the keys are unique identifiers for ‘ViewModel’ instances, and the values are the ‘ViewModel’ instances themselves.

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

The ‘put()’ method stores a ‘ViewModel’ instance in the ‘HashMap’ with the provided key. If a ‘ViewModel’ with the same key already exists, it’s replaced, and it’s ‘onCleared()’ method is called. This ensures that any resources held by the replaced ‘ViewModel’ are properly released.

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

The ‘get()’ method retrieves the ‘ViewModel’ instance associated with the provided key. If no ‘ViewModel’ is associated with this key, it returns ‘null’.

fun clear() {
for (viewModel in map.values) {
viewModel.onCleared()
}
map.clear()
}

The ‘clear()’ method iterates through all the ‘ViewModel’ instances in the ‘HashMap’, calls their ‘onCleared()’ methods, and then clears the ‘HashMap’. This method is typically called when the final lifecycle owner that the ‘ViewModelStore’ is attached to (such as an ‘Activity’ or ‘Fragment’) is being permanently destroyed.

Conclusion

Understanding ‘ViewModelStore’ is critical to grasping how ‘ViewModels’ survive configuration changes. Even though we don’t interact with it directly in our daily coding, this under-the-hood knowledge can give you a broader perspective of Android’s ‘ViewModel’ system and help you debug tricky issues related to lifecycle handling.

In your Android journey, never stop exploring and learning about the internals of the tools and libraries you use. It will help you become a more effective and knowledgeable developer. Happy coding!

Also Check:

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.