Understanding ViewModelProvider: A Deep Dive

Milind Amrutkar
4 min readJun 28, 2023

--

Photo by Marco Assmann on Unsplash

Introduction

In the realm of Android Development, managing lifecycle events is crucial. For that, Google provides the ViewModel component, which helps handle data in a lifecycle-conscious way. But have you ever wondered about the role of the ViewModelProvider and what it does? Let’s break down its functionality, exploring the ViewModelProvider line by line.

ViewModelProvider: The Basics

The ViewModelProvider is a utility class that provides ViewModel instances. With the ViewModelProvider, you can create ViewModels, get existing ViewModels, and associate them with your activities, fragments, or navigation graphs. This association ensures that you always get the correct ViewModel instance, even if the activity or fragment is recreated due to configuration changes.

Exploring the ViewModelProvider Code

Let’s explore a simplified version of the ViewModelProvider’s implementation:

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

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

class ViewModelProvider(
private val store: ViewModelStore,
private val factory: Factory) {

The ViewModelProvider class requires a ViewModelStore and a Factory. The ViewModelStore is responsible for storing and retrieving ViewModel instances, while the Factory is used to instantiate a new ViewModel when needed.

fun <T: ViewModel> get(modelClass: Class<T>): T {
var viewModel = store.get(modelClass.name)

The ‘get()’ method is used to retrieve a ViewModel. This method takes a Class object, which is used to identify and return an existing ViewModel associated with that class, if it exists.

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

If there’s no existing ViewModel, it uses the factory to create a new instance, and then it stores the new instance in the ViewModelStore. The class name of the ViewModel is used as the key to store the instance.

return viewModel as T

Finally, it returns the ViewModel. The cast is safe because the factory is expected to create a ViewModel of the correct type.

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

The Factory interface has a single method, ‘create()’, responsible for instantiating ViewModels. When you implement this interface, you should return an instance of the ViewModel identified by the provided Class.

Conclusion

Understanding how the ViewModelProvider works gives you a stronger grasp of the Android ViewModel architecture. Remember, the ViewModelProvider acts as a bridge connecting the ViewModelStore and your activites or fragments. It ensures that you always get the correct ViewModel instance, even when configuration changes occur. So, whenever you’re dealing with ViewModels, think about the trusty ViewModelProvider working behind the scenes to make your life easier. 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.