In Jetpack Lifecycle, how do you write a ViewModelProvider.Factory with CreationExtras for a ViewModel needing a repository, a branch id and a SavedStateHandle?
answer
- the default factory's constructor limits
- a stateless factory reads extras
- viewModelFactory with an initializer
- CreationExtras.Key plus createSavedStateHandle()
- custom extras must start from the owner's defaults
basics
~20 sDefine viewModelFactory { initializer { } } whose lambda reads the Application from APPLICATION_KEY, the branch id from a custom CreationExtras.Key and calls createSavedStateHandle(). Pass the branch id in extras built on the owner's default extras.
solid answer
~40 sThe default factory only handles a no-argument constructor, a `SavedStateHandle` one or an `AndroidViewModel`, so this ViewModel needs a `ViewModelProvider.Factory`. Its `create(modelClass, extras)` gets everything from `CreationExtras`, which keeps the factory stateless: I write it as `viewModelFactory { initializer { ... } }`, read the repository through `this[APPLICATION_KEY]`, the branch id through a custom `CreationExtras.Key<String>()`, and call `createSavedStateHandle()`. At the call site I pass the factory plus extras built on the owner's defaults, `CreationExtras(owner.defaultViewModelCreationExtras) { this[BRANCH_ID_KEY] = id }`; bare extras lose the keys `createSavedStateHandle()` needs and it throws `IllegalArgumentException`. The factory runs only when the owner's store has no instance for the key, so later extras are ignored. `AbstractSavedStateViewModelFactory`, the old route, has been deprecated since Lifecycle 2.9.
code
kotlin · 20 linesclass BookingViewModel(
private val prices: PriceRepository,
private val branchId: String,
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
companion object {
val BRANCH_ID_KEY = CreationExtras.Key<String>()
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as RentalApp
BookingViewModel(
prices = app.priceRepository,
branchId = checkNotNull(this[BRANCH_ID_KEY]),
savedStateHandle = createSavedStateHandle(),
)
}
}
}
}go deeper
Recall that a ViewModel with constructor dependencies needs a ViewModelProvider.Factory, and that viewModelFactory with initializer is the Kotlin way to write one.
Explain the standard CreationExtras keys, a custom CreationExtras.Key, createSavedStateHandle() and why extras keep the factory stateless.
Spot extras that drop the owner's defaults, a branch change that never reaches a cached ViewModel, and a deprecated AbstractSavedStateViewModelFactory still in use.
Decide whether a team hand-writes factories with CreationExtras or generates them through dependency injection, and where the shared keys live.
## Why a factory at all The framework, not your code, creates ViewModels, because only the provider knows whether an instance already sits in the owner's `ViewModelStore`. The **default factory** can build three shapes of class by reflection: - a no-argument constructor; - a constructor taking only a `SavedStateHandle`; - an `AndroidViewModel` taking an `Application`, with or without a `SavedStateHandle`. A booking ViewModel that needs a price repository and a branch id fits none of them, so it needs a **`ViewModelProvider.Factory`**. The class documentation is blunt: never create a ViewModel outside such a factory. ## CreationExtras: the factory's inputs `Factory.create(modelClass, extras)` receives a **`CreationExtras`**, a read-only map from typed `CreationExtras.Key<T>` objects to values. Because each request brings its inputs, the factory itself holds no state and can be a single object. The owner fills in standard keys: | Key | Holds | |---|---| | `APPLICATION_KEY` | the `Application` | | `VIEW_MODEL_KEY` | the key the ViewModel will be stored under | | `SAVED_STATE_REGISTRY_OWNER_KEY` | the owner whose saved state backs the handle | | `VIEW_MODEL_STORE_OWNER_KEY` | the owner whose store will hold the ViewModel | | `DEFAULT_ARGS_KEY` | the arguments used to seed a `SavedStateHandle` | `CreationExtras.createSavedStateHandle()` reads the second, third and fourth of these and throws **`IllegalArgumentException`** naming the missing key when one is absent. ## Writing the factory The Kotlin DSL is `viewModelFactory { initializer { ... } }`. Each `initializer` lambda has `CreationExtras` as its receiver, so `this[APPLICATION_KEY]` and `createSavedStateHandle()` work directly. A custom input gets its own key, created once with `CreationExtras.Key<String>()`. By convention the key and the factory live in the ViewModel's companion object, so callers find them next to the class. ## Passing the branch id In Compose, `viewModel(factory = ..., extras = ...)` takes the extras explicitly, and its default value is the owner's `defaultViewModelCreationExtras`. Replacing that default with a fresh `CreationExtras { }` drops `APPLICATION_KEY` and the saved-state keys, so the initializer fails. Build on the defaults instead: 1. read the owner, for example `LocalViewModelStoreOwner.current`; 2. call `CreationExtras(owner.defaultViewModelCreationExtras) { this[BRANCH_ID_KEY] = branchId }`, or use the `+` operator on two extras; 3. pass the factory and those extras to `viewModel()`. An Activity or Fragment can instead override `defaultViewModelCreationExtras` and add the key there, so `by viewModels(...)` with the factory sees it too. The override suits a value fixed for the owner's whole life, such as the branch an Activity was launched for; per-call extras suit a value that only one composable knows. Either way, start from `super`'s extras or the owner's defaults and add to them, never from an empty set. ## The factory runs once per key The provider calls the factory only when the store has no instance of that class under the key. Asking again with different extras for the same owner and key returns the **existing** ViewModel; the new branch id never arrives. When one owner must hold one booking per branch, pass a distinct `key` such as the branch id; when the branch is fixed for the screen's life, the default key is fine. ## Failures worth recognising - **A key created twice.** `CreationExtras.Key<String>()` returns a new, unique key object on every call, and lookups compare keys by identity. A key written as a property getter, or created separately at the call site and in the factory, never matches, so `this[BRANCH_ID_KEY]` returns `null`. Create it once, in the companion object. - **A missing custom value.** `checkNotNull(this[BRANCH_ID_KEY])` fails with `IllegalStateException`, which is better than a ViewModel quietly built for no branch. - **An owner without defaults.** An owner that does not implement `HasDefaultViewModelProviderFactory` contributes `CreationExtras.Empty`, so `APPLICATION_KEY` and the saved-state keys are absent unless you supply them. - **One factory for several ViewModels.** A single `viewModelFactory` block may hold one `initializer` per class, which suits ViewModels that share dependencies; a second initializer for the same class fails with `IllegalArgumentException`. ## What changed across releases - `AbstractSavedStateViewModelFactory` is **deprecated since Lifecycle 2.9**: it created a `SavedStateHandle` for every ViewModel, even those that never used one. Its replacement is exactly this pattern. - Lifecycle 2.9 added map-like operators on `CreationExtras` (`in`, `+`, `+=`) and the `CreationExtras.Key()` factory function. - Lifecycle 2.10 added the `CreationExtras(initialExtras) { }` builder function. - Lifecycle 2.11 added `defaultViewModelCreationExtras` and `defaultViewModelProviderFactory` as extensions on any `ViewModelStoreOwner`, so code no longer checks for `HasDefaultViewModelProviderFactory` itself. A dependency-injection framework can generate these factories for you; the extras mechanism underneath is the same.
- Why read the branch id from CreationExtras instead of passing it to the factory's constructor?A constructor parameter works, but then each branch needs a new factory object and the factory carries per-screen state. `CreationExtras` exists so one stateless factory serves every request, reading per-request inputs at creation time. Either way the factory runs only once per store key, so changing the input later still needs a distinct key.
- How do you test a ViewModel whose factory calls createSavedStateHandle()?Test the ViewModel class directly: construct it with a fake repository, a branch id and `SavedStateHandle(mapOf(...))`, the constructor meant for tests. The factory is thin glue; if you test it, give it `CreationExtras` that carry every key `createSavedStateHandle()` reads.
- Every ViewModel needs a custom factory, even one taking only a SavedStateHandle.
- Passing new extras to viewModel() recreates the ViewModel with the new value.
- A bare CreationExtras {} block is merged with the owner's defaults automatically.
- AbstractSavedStateViewModelFactory is still the recommended way to get a SavedStateHandle.
- Each call to viewModel() runs the factory's initializer again.
Assumes Lifecycle 2.11; AbstractSavedStateViewModelFactory is deprecated since 2.9, the CreationExtras builder function arrived in 2.10 and the ViewModelStoreOwner.defaultViewModelCreationExtras extension in 2.11.