Skip to content
Go back

Android ViewModel Internals — ViewModelProvider, ActivityThread, and the Factory Pattern

Android ViewModel Internals — ViewModelProvider, ActivityThread, Factory

The previous post built a ViewModel prototype using an Application-level HashMap, revealing the two rules a ViewModel must follow: store in a longer-lived class, clear only on permanent destruction. Android’s official implementation follows the same rules with a more complete architecture. This post walks through the full internal chain.


The Full Internal Chain

When you write:

viewModel = ViewModelProvider(this)[MainViewModel::class.java]

Five components are involved:

Activity → ViewModelProvider → ComponentActivity → NonConfigurationInstance → ViewModelStore

Each component has a specific role.


ComponentActivity and NonConfigurationInstance

Your Activity does not extend Activity directly — it extends ComponentActivity, which itself extends Activity. ComponentActivity is where the ViewModel infrastructure lives.

Inside ComponentActivity there is a static class called NonConfigurationInstance. It holds two things:

ViewModelStore is essentially the same HashMap that was built in the prototype: a map of String keys to ViewModel instances.

Before ViewModel existed, persisting data across configuration changes required onSaveInstanceState(). NonConfigurationInstance and its custom object were the mechanism behind that. ViewModelStore is the modern replacement — same concept, better design.


ActivityThread — The Lifecycle Manager

ActivityThread is the most important piece of the puzzle, and also the most misunderstood.

ActivityThread is not a Java thread. Despite the name, it is a class — a manager class that Android’s operating system uses to control the lifecycle of all components in your application. It is created before your Application object. Its lifecycle extends beyond both the Application and any individual Activity.

Inside ActivityThread there is a method called performDestroyActivity(). When any Activity is destroyed, this method runs. It knows why the Activity is being destroyed — whether because of a configuration change or a permanent exit. That is the system-level equivalent of isChangingConfigurations.

ActivityThread is responsible for temporarily holding NonConfigurationInstance during configuration changes and handing it back to the newly created Activity. No data is lost because the store never left — it was held at a level above the Activity.


Three Lifecycle Scenarios

Scenario 1 — First Launch

  1. Activity calls ViewModelProvider(this).
  2. ViewModelProvider checks ComponentActivity for an existing ViewModel.
  3. NonConfigurationInstance is empty — no ViewModel yet.
  4. ViewModelProvider creates a new ViewModel (via Factory or reflection).
  5. The ViewModel is stored in ViewModelStore inside NonConfigurationInstance.
  6. The ViewModel is returned to the Activity.

Scenario 2 — Configuration Change (Rotation, Font Size, Language)

  1. Configuration change occurs. Activity is destroyed.
  2. ActivityThread detects this is a configuration change and holds onto NonConfigurationInstance — it does not discard it.
  3. A new Activity instance is created. onCreate() runs.
  4. ActivityThread reassigns the same NonConfigurationInstance to the new ComponentActivity.
  5. Activity calls ViewModelProvider(this) again.
  6. ViewModelStore already contains the ViewModel — it is returned directly.

The data is intact because the store was never cleared. It was transferred between Activity instances by ActivityThread.

Scenario 3 — Permanent Destruction

  1. Activity is destroyed without a configuration change (user presses back, finish() called).
  2. ActivityThread recognizes this is a permanent destroy — it does not reassign NonConfigurationInstance.
  3. onDestroy() runs. ViewModelStore.clear() is called.
  4. ViewModel.onCleared() is invoked — the place to cancel coroutines and release resources.
  5. The ViewModel is removed from memory.

No memory leak. No stale data. The ViewModel’s lifetime ends exactly when its owner’s lifetime ends.


ViewModelProvider Without a Factory

The simplest usage passes no factory:

viewModel = ViewModelProvider(this)[MainViewModel::class.java]

When no factory is provided and the ViewModel does not exist yet, ViewModelProvider uses a default factory that creates the ViewModel via reflection:

fun <T> getViewModel(modelClass: Class<T>): T {
    return modelClass.getDeclaredConstructor().newInstance()
}

The class reference (MainViewModel::class.java) is passed to the method. The method calls getDeclaredConstructor().newInstance() — a runtime operation that finds the no-argument constructor and calls it.

Reflection is slower than direct instantiation because it scans the class structure at runtime. For ViewModel creation — which happens at most once per Activity instance — this overhead is negligible.


When Is a Factory Required?

The rule is simple:

Zero constructor parameters → no factory needed. One or more parameters → factory required.

// No factory needed — default reflection handles this
class MyViewModel : ViewModel()

// Factory required — reflection cannot supply constructor arguments
class MyViewModel(val repo: Repository) : ViewModel()

Reflection can only call a no-argument constructor. If the ViewModel needs a Repository, a UseCase, or any dependency injected through the constructor, the default mechanism cannot create it. A custom factory is required:

class MyViewModelFactory(private val repo: Repository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return MyViewModel(repo) as T
    }
}

// Usage
viewModel = ViewModelProvider(this, MyViewModelFactory(repository))[MyViewModel::class.java]

The factory is the Factory design pattern applied to ViewModel creation. It is not Android-specific — the Factory pattern is a general design pattern for creating objects without specifying the exact class at the call site. In Android, ViewModelProvider.Factory is the standard interface for this.


The Double-Colon Operator

In the reflection example, MainViewModel::class.java appears frequently. The double colon (::) is Kotlin’s class reference operator.

Both refer to the same class. The .java conversion is required when passing the reference to APIs that expect a Java Class.


ActivityThread Is Not the Main Thread

A common source of confusion: ActivityThread sounds like the main thread. It is not. The main thread (UI thread) is a Thread object in the Java sense. ActivityThread is a separate class that manages the lifecycle of Android components. It runs its event-processing loop on the main thread, but the class itself is distinct from the thread.

In short:

ActivityThreadMain thread
TypeClass (component manager)Java Thread
CreatedBefore ApplicationWhen process starts
PurposeManage Activity lifecycleExecute UI operations
LifecycleEntire process lifetimeEntire process lifetime

Summary

Activity → ViewModelProvider → ComponentActivity
                                      ↓
                          NonConfigurationInstance
                                      ↓
                              ViewModelStore (HashMap)
                                      ↓
                                  ViewModel
                                      ↑
                     ActivityThread (holds during config changes)

Share this post on:

Previous Post
Lambdas, Higher-Order Functions, and Typealias in Kotlin
Next Post
Android ViewModel Internals — Why Data Gets Lost on Rotation and How to Fix It