🧙 ViewModel Factory: Your Personal Recipe Book! 🧙

taimur tanveer
2 min readAug 25, 2023

ViewModelFactory is a class in Android that's responsible for creating instances of ViewModel classes with a customized configuration or initialization. It allows you to pass parameters or dependencies to your ViewModel when it's being created. This is particularly useful when you ViewModel require additional data beyond the default empty constructor.

Just take a recipe book example:

Think of a ViewModel Factory in Android as your very own recipe book 📖. It helps you create special ViewModels with specific ingredients 🍳 to make them unique and super useful.

🌟 Benefits of the ViewModel Factory: 🌟

  1. Parameterized Initialization:
    With a ViewModelFactory, you can add special stuff to your ViewModels, like passing numbers, words, or even tools they need.
  2. Decoupling from Android Components:
    Using a ViewModelFactory keeps things organized. It separates your ViewModelfrom the place you’re using it. This makes it easier to test and fix.
  3. Code Reusability:
    A ViewModelFactory allows you to create multiple instances of the same ViewModel class with different parameters, enabling code reusability in various parts of your app.

🧪 Where to Use ViewModel Factory: 🧪

You should use a ViewModelFactory when you need to initialize a ViewModel with parameters, especially when these parameters are not readily available at the time of the ViewModel creation. This is common when you want to pass data from a parent fragment to a child fragment's ViewModel but on the other hand, it all depends upon your project usage.

Let’s dive into the coding realm! 🚀👨‍💻

Suppose we have a scenario where we want to create a CountViewModel that takes an initial count value as a parameter.

Step 1: Create the ViewModel🌟

import androidx.lifecycle.ViewModel

class CountViewModel(private val initialCount: Int) : ViewModel() {
var count = initialCount
private set

fun increment() {
count++
}
}

Step 2: Create the ViewModelFactory🏰

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

class CountViewModelFactory(private val initialCount: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(CountViewModel::class.java)) {
return CountViewModel(initialCount) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}

Step 3: Use the ViewModelFactory in Your Fragment or Activity 🔮

In your Fragment or Activity, when you need to create a CountViewModel instance with a specific initial count value, you'll use the CountViewModelFactory.

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

private lateinit var viewModel: CountViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val initialCount = 10 // The initial count value you want to pass

val viewModelFactory = CountViewModelFactory(initialCount)
viewModel = ViewModelProvider(this, viewModelFactory).get(CountViewModel::class.java)

updateCountText()

incrementButton.setOnClickListener {
viewModel.increment()
updateCountText()
}
}

private fun updateCountText() {
countTextView.text = viewModel.count.toString()
}
}

In this example, the CountViewModel requires an initialCount parameter to be created. We create a CountViewModelFactory that takes this parameter and passes it to the ViewModelProvider when creating the CountViewModel instance.

By using the ViewModelFactory, you’re able to pass the required parameters to your ViewModel’s constructor, keeping your ViewModel’s initialization logic clean and flexible.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response