skip to content

In a modular Android app on plain Dagger, how do @IntoMap and a map key let feature modules contribute ViewModel providers to one factory?

level: seniorimportance: nice to knowfreq 25%

answer

  1. many modules, one collection
  2. keys known at compile time
  3. inject Map<K, Provider<V>>
  4. empty collections need declaring
  5. duplicate keys fail the build

basics

~20 s

Each feature module adds one entry with an @IntoMap binding plus a key annotation such as @ClassKey; Dagger assembles a Map<Class<*>, Provider<ViewModel>> that a single ViewModelProvider.Factory injects and looks up by class, without knowing any feature.

solid answer

~40 s

Dagger multibindings let several modules contribute to one collection. For a map, each contribution is a `@Provides` or `@Binds` method marked `@IntoMap` plus a key annotation: `@StringKey`, `@ClassKey`, `@IntKey`, `@LongKey`, or a custom one meta-annotated with `@MapKey`. Every feature module binds its `ViewModel` with `@IntoMap @ClassKey(CheckoutViewModel::class)`, and one `ViewModelProvider.Factory` injects `Map<Class<*>, @JvmSuppressWildcards Provider<ViewModel>>`; injecting `Provider` values means only the requested ViewModel gets built, and fresh each time. Keys must be known at compile time, and a duplicate key inside a component fails the build. If the map can be empty, declare it with an abstract `@Multibinds` method, or the injection is a missing binding. On Android, `@LazyClassKey` avoids loading every key class when the map is built.

code

kotlin · 38 lines
kotlin
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Binds
import dagger.Module
import dagger.multibindings.ClassKey
import dagger.multibindings.IntoMap
import dagger.multibindings.Multibinds
import javax.inject.Inject
import javax.inject.Provider

class CheckoutViewModel @Inject constructor() : ViewModel()

// :feature-checkout
@Module
abstract class CheckoutViewModelModule {
    @Binds
    @IntoMap
    @ClassKey(CheckoutViewModel::class)
    abstract fun bindCheckout(vm: CheckoutViewModel): ViewModel
}

// :core-ui, installed in the app component
@Module
abstract class ViewModelMapModule {
    @Multibinds
    abstract fun viewModels(): Map<Class<*>, ViewModel> // legal even if no feature contributes
}

class AppViewModelFactory @Inject constructor(
    private val creators: Map<Class<*>, @JvmSuppressWildcards Provider<ViewModel>>,
) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = creators[modelClass]
            ?: throw IllegalArgumentException("No ViewModel bound for $modelClass")
        @Suppress("UNCHECKED_CAST")
        return creator.get() as T
    }
}

go deeper

for a junior

Recall that @IntoSet and @IntoMap let several modules feed one injected collection, and that map entries need a key annotation such as @ClassKey.

for a middle

Explain why the factory injects Map<Class<*>, Provider<ViewModel>>, what @Multibinds is for, and why keys must be compile-time constants.

for a senior

Diagnose the real failures: a Kotlin wildcard missing binding, a duplicate key, an empty map in a test component, and entries hidden inside a subcomponent.

for a principal

Judge when a plugin map is worth it versus direct bindings, and when Hilt's ViewModel support or @LazyClassKey changes the startup and readability trade-off.

## Multibindings: one collection, many contributors A **multibinding** lets bindings from different modules feed one injectable collection, so the code that consumes the collection never imports the contributors. That is the shape of a plugin system: a central class depends on "all the handlers" or "all the ViewModels", and each feature module adds its own. Dagger has two collection shapes: | Collection | Contribute one element | Contribute several at once | Duplicates | |---|---|---|---| | `Set<T>` | `@IntoSet` | `@ElementsIntoSet` returning a `Set<T>` | Allowed; standard `Set` semantics keep one | | `Map<K, V>` | `@IntoMap` plus a key annotation | none | A duplicate key is a compile error | Contributions are ordinary `@Provides` or `@Binds` methods with the extra annotation. To contribute to a **qualified** collection, put the qualifier on each contribution and on the injection site. ## Map keys A map entry needs its key spelled in an annotation, which is why **keys must be known at compile time**: - **`@StringKey`, `@IntKey`, `@LongKey`, `@ClassKey`** in `dagger.multibindings` cover strings, boxed primitives and `Class<?>` keys. - **A custom `@MapKey` annotation** with one member covers enums or a more specific class type, for example `Class<out ViewModel>`. - **`@MapKey(unwrapValue = false)`** makes the whole annotation instance the key, for keys with several members. - **`@LazyClassKey`** produces a class-keyed map that is a string-keyed map underneath, so key classes load only when looked up. It cannot serve `keySet()` or `entrySet()`, an unqualified one cannot coexist with `@ClassKey`, and Dagger pairs it with R8 and ProGuard configuration because it depends on class names. When keys are only known at runtime, contribute `Map.Entry` objects with `@IntoSet` and build an ordinary map from the set yourself. ## The ViewModel factory pattern On Android without Hilt, a common use is a single `ViewModelProvider.Factory` for the whole app: 1. Each feature module binds its ViewModel into the map with `@Binds @IntoMap @ClassKey(CheckoutViewModel::class)`. 2. The factory injects `Map<Class<*>, @JvmSuppressWildcards Provider<ViewModel>>` and, in `create(modelClass)`, looks up the class and calls `get()`. 3. Because the values are `Provider`s, only the requested ViewModel is constructed, and each lookup builds a new one, which is what `ViewModelProvider` expects since it caches the ViewModel itself. The factory is an ordinary `@Inject` class, so a screen receives it through members injection and passes it to `ViewModelProvider(this, factory)`. Adding a feature means adding one module with one `@IntoMap` method; neither the factory nor the application component's code changes, only the module list the component installs. For any `Map<K, V>` multibinding Dagger also offers `Map<K, Provider<V>>`, useful when you do not want every value instantiated or want a potentially new value per query. You cannot request `Set<Provider<T>>` for a set multibinding. ## Declaring collections that may be empty A multibound collection exists as soon as one contribution exists. If no module contributes, for example in a test component or a build flavour without any feature, the injection is a missing binding. Declare it with an abstract method annotated `@Multibinds` in a module: - `@Multibinds abstract fun viewModels(): Map<Class<*>, ViewModel>` declares the map; Dagger never implements or calls the method. - A collection may be declared any number of times without error. - For sets only, an `@ElementsIntoSet` method returning an empty set is an alternative. ## Pitfalls specific to Kotlin and subcomponents - **Wildcards.** Kotlin may expose `Map<Class<*>, Provider<ViewModel>>` to Dagger as a map whose values are `? extends` types, and Dagger then reports `[Dagger/MissingBinding]` for that wildcard type. The documented fix is `@JvmSuppressWildcards` on the value type at the injection site. - **Subcomponent contributions.** A subcomponent can add entries to a map or set bound in its parent; those entries are visible only to bindings inside that subcomponent and its descendants. A factory injected in the parent sees only the parent's entries, so a ViewModel bound in a screen subcomponent is missing from an application-wide factory. - **Duplicate keys across a component boundary.** Within one component a duplicate key fails with `The same map key is bound more than once`. Across a parent and subcomponent, Dagger keeps a lenient legacy behaviour unless you opt in with `-Adagger.mapMultibindingDuplicateDetectionFix=ENABLED`. - **Over-using the map.** Every contribution makes the consumer's map larger and the graph harder to read; a single binding is simpler when there is only one implementation.

  • A Dagger ViewModel factory injected in the application component cannot find a ViewModel whose @IntoMap binding sits in a screen subcomponent's module: why?
    Entries a subcomponent adds to a parent's multibound map are visible only to bindings inside that subcomponent and its descendants. The factory resolved in the application component sees only the application component's entries. Move the contribution up, or resolve the factory inside the subcomponent.
  • Why might an Android app choose @LazyClassKey over @ClassKey for a large Dagger map?
    Building a `@ClassKey` map loads every key class, which can cost startup time on Android. `@LazyClassKey` stores class names under the hood and loads a class only on lookup. The trade-offs: no `keySet()` or `entrySet()`, no mixing with an unqualified `@ClassKey`, and reliance on the R8 or ProGuard configuration Dagger supplies.

  • Two modules may bind the same map key and the last one wins.
  • An empty Dagger multibound map is injectable without any declaration.
  • Map keys can be computed at runtime from a config value.
  • Set<Provider<T>> works the same way Map<K, Provider<V>> does.
  • A subcomponent's map entries are visible to bindings in its parent.