Skip to content
Public template

About

KMP base project with Umbrella and different options

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

UmbrellaTemplate

Advanced KMP starter — modular observability (api / spi / impl), Metro DI, and Firebase (Android + iOS SPM). Not a minimal blank Compose app; see shared/README.md for architecture rationale.

Kotlin Multiplatform starter with modular observability (api / spi / impl), Metro DI composition in shared:di, and an iOS-only shared:umbrella framework. Targets Android, iOS, Desktop (JVM), JS, and Wasm.

For architecture decisions and provider options, see shared/README.md. For broader modularization context, see Android at scale @Square. For clone/setup/rename/Firebase, see docs/TEMPLATE.md. To contribute, see CONTRIBUTING.md.

Kotlin 2.4.0-RC is required today for iOS Firebase via Kotlin swiftPMDependencies. Upgrade to stable 2.4.x in gradle/libs.versions.toml when available.

Prerequisites

Module map

This project follows the new JetBrains KMP default structure: one shared UI library + per-platform entry-point modules.

Module Role
sharedUI Compose Multiplatform UI library — consumed by androidApp, desktopApp, webApp
androidApp Android application entry point (Firebase plugins applied here)
desktopApp Desktop (JVM) Compose application
webApp Browser (JS + Wasm) Compose application
iosApp Xcode/SwiftUI application; links SharedUmbrella.framework
shared:di Metro graphs and factories — use on Android/desktop/web
shared:umbrella SharedUmbrella.framework + API exports — iOS only; the app modules must not depend on it
platform-observability-firebase Firebase SPI adapters and bindings
platform-observability-noop No-op observability for JVM / JS / Wasm
shared/observability api, spi, impl feature slices
shared/core Domain, foundation, logger modules
build-logic Convention plugins

Architecture (short)

  • Android / JVM / JS / Wasm app modules depend on sharedUI (Compose UI) + shared:di (Metro graphs); feature code uses observability-api types via sharedUI's api exposure.
  • iOS: iosApp links SharedUmbrella; Swift calls IosAppDependencyGraphFactory (exported from shared:di through umbrella).
  • Providers (platform-observability-*) supply bindings only; they do not own the app graph.

Each app module (androidApp, desktopApp, webApp) has a Gradle guard that prevents accidental dependencies on :shared:umbrella.

Metro DI

This template uses Metro with aggregation (Anvil-style): implementations in feature/provider modules contribute into a single app scope graph in shared:di. The KMP convention plugin enables generateContributionHints so bindings merge across modules without listing every class on the graph.

Official docs: Quick Start · Aggregation · Bindings / multibindings

Mental model

Piece Role in this repo
@DependencyGraph(scope = …) Declares the app graph; Metro merges all contributions for that scope
@ContributesBinding “This class is the one implementation of interface X”
@ContributesIntoSet “This class is one of many implementations collected into Set<X>”
@IntoSet / @ElementsIntoSet Same set contribution, but from a @Provides / @Binds in a @BindingContainer
@ContributesTo + @BindingContainer “This module object provides things Metro cannot construct from a constructor” (@Provides)
@Inject Optional on @Contributes* types (implicit inject is on by default); required when you have multiple constructors
binding<Interface>() Use when the bound type is not the only supertype, or you need an explicit binding target

Rule of thumb: prefer @ContributesBinding / @ContributesIntoSet on your own types; use @ContributesTo + @Provides (with @IntoSet when needed) only for third-party SDKs, factories, or conditional wiring.

1. App graph (shared:di)

The graph declares scope only — no bindingContainers list. Platform-specific graphs pick up whatever is on their compile classpath (Firebase on Android/iOS, noop on JVM/JS/Wasm).

@DependencyGraph(scope = AppScope::class)
interface AndroidDependencyGraph : BaseDependencyGraph {

    @DependencyGraph.Factory
    fun interface Factory {
        fun create(): AndroidDependencyGraph
    }
}

Expose dependencies via graph interfaces (ObservabilityGraph, BaseDependencyGraph), then create the graph from the app:

val graph = AndroidDependencyGraphFactory.createGraph()
graph.analyticsLogger.track(myEvent)

2. @ContributesBinding — your implementations

Use on classes you own: feature impl (DefaultAnalyticsLogger), platform adapters (FirebaseAnalyticsPlatform), or no-ops (NoOpAnalyticsLogger).

Metro injects constructor parameters automatically; @Inject is optional unless you need to be explicit.

@ContributesBinding(
    scope = AppScope::class,
    binding = binding<AnalyticsLogger>(),
)
class DefaultAnalyticsLogger(
    private val platform: AnalyticsPlatform,
) : AnalyticsLogger { /* … */ }

Platform adapter (SPI) — same pattern; Firebase SDK types come from a @Provides container (below):

@ContributesBinding(
    scope = AppScope::class,
    binding = binding<AnalyticsPlatform>(),
)
class FirebaseAnalyticsPlatform(
    private val firebase: FirebaseAnalytics,
) : AnalyticsPlatform { /* … */ }

Use binding<SomeInterface>() when the implementation has multiple supertypes or you bind to an interface that is not the only parent.

3. @ContributesTo + @BindingContainer + @Provides — manual wiring

Use when there is no injectable constructor: third-party SDK entry points, object factories, or choosing between qualified bindings.

@ContributesTo(AppScope::class)
@BindingContainer
object FirebaseSdkBindings {

    @Provides
    fun provideFirebaseAnalytics(): FirebaseAnalytics = Firebase.analytics
}

Debug vs release selection (qualifiers @Debug / @Release on contributed CrashPlatform types):

@ContributesTo(AppScope::class)
@BindingContainer
object FirebaseObservabilityBindings {

    @Provides
    fun provideCrashPlatform(
        @Debug debugVersion: CrashPlatform,
        @Release releaseVersion: CrashPlatform,
    ): CrashPlatform = if (isDebug) debugVersion else releaseVersion
}

Kermit Logger is provided here; DefaultKMPLogger is a @ContributesBinding that receives it — see LoggerBindings.

4. @ContributesIntoSet / @IntoSet — multibindings (many of one type)

Use when you need several implementations of the same type collected into an immutable Set<T> — feature plugins, screen registrations, validators, initializers. Prefer this over @ContributesBinding when “one winner” is the wrong model and each module should add an entry without a central registry.

Official docs: Aggregation — @ContributesIntoSet · Bindings — Multibindings

Pattern: plugin interface → @ContributesIntoSet → fold Set<T> on the graph

This is the registration style used for multi-feature screens (e.g. a PresenterRegistration / UiRegistration plugin per feature module):

  1. Define a small plugin interface in an api module.
  2. Each feature impl contributes one class with @ContributesIntoSet(SomeScope::class).
  3. The @DependencyGraph for that scope injects Set<Plugin> into a @Provides and folds it (often firstNotNullOfOrNull) into a single factory / facade the app consumes.
/** API module — one plugin per feature; return null if you don't handle the request. */
fun interface PresenterRegistration {
    fun create(screen: Screen, navigator: Navigator): Presenter<*>?
}

/** Feature impl — contributes into AppScope Set<PresenterRegistration>. */
@ContributesIntoSet(AppScope::class)
class AuthPresenterRegistration(
    private val repository: AuthRepository,
) : PresenterRegistration {
    override fun create(screen: Screen, navigator: Navigator): Presenter<*>? =
        when (screen) {
            is SignInScreen -> SignInPresenter(repository, navigator)
            else -> null
        }
}

/** Another feature — same set, no central list to update. */
@ContributesIntoSet(AppScope::class)
class HomePresenterRegistration(
    private val repository: HomeRepository,
) : PresenterRegistration { /* … */ }

/**
 * Graph for that scope — Metro aggregates every @ContributesIntoSet contribution
 * into registrations: Set<PresenterRegistration>, then you fold it once.
 */
@DependencyGraph(AppScope::class)
interface AppGraph {
    val presenterFactory: Presenter.Factory

    @Provides
    fun providePresenterFactory(
        registrations: Set<PresenterRegistration>,
    ): Presenter.Factory =
        object : Presenter.Factory {
            override fun create(
                screen: Screen,
                navigator: Navigator,
                context: CircuitContext,
            ): Presenter<*>? =
                registrations.firstNotNullOfOrNull { it.create(screen, navigator) }
        }
}

Scoped sets: contribute to different scopes when the plugins should not mix. Example: @ContributesIntoSet(AppScope::class) for signed-out screens, @ContributesIntoSet(UserScope::class) for signed-in screens, with a child @DependencyGraph(UserScope::class) that folds its own Set<PresenterRegistration>:

@DependencyGraph(UserScope::class)
interface UserGraph {
    val presenterFactory: Presenter.Factory

    @Provides
    fun providePresenterFactory(
        registrations: Set<PresenterRegistration>,
    ): Presenter.Factory =
        object : Presenter.Factory {
            override fun create(
                screen: Screen,
                navigator: Navigator,
                context: CircuitContext,
            ): Presenter<*>? =
                registrations.firstNotNullOfOrNull { it.create(screen, navigator) }
        }
}

@ContributesIntoSet(UserScope::class)
class HomePlaceholderPresenterRegistration(
    private val sessionHandle: AuthSessionHandle,
) : PresenterRegistration { /* only present after sign-in */ }

Metro notes that matter for this pattern:

  • One declared supertype → that type is the set element. Multiple supertypes → binding = binding<PresenterRegistration>().
  • Set contributions are additive and do not support priority. Use replaces = […] or graph excludes to drop a contribution.
  • Empty multibindings are a compile error by default. If the set may be empty, declare @Multibinds(allowEmpty = true) on the accessor.
  • Keep generateContributionHints (and generateContributionHintsInFir when aggregating into Native/iOS graphs) on so feature modules’ set contributions are visible to the graph module.

When to use @IntoSet / @ElementsIntoSet instead

@ContributesIntoSet is for your injectable classes (the registration pattern above). Use @Provides + @IntoSet (or @ElementsIntoSet) in a @ContributesTo @BindingContainer when the contribution is not a constructable type you own — SDK values, adapters without @Inject, or providing several elements at once:

@ContributesTo(AppScope::class)
@BindingContainer
object ExtraRegistrationBindings {

    @Provides
    @IntoSet
    fun provideLegacyRegistration(): PresenterRegistration = LegacyPresenterRegistration()

    @Provides
    @ElementsIntoSet
    fun providePlatformRegistrations(): Set<PresenterRegistration> =
        setOf(PlatformARegistration(), PlatformBRegistration())
}

Class-level @ContributesIntoSet and container @IntoSet / @ElementsIntoSet merge into the same Set<T> for that scope.

Map multibindings (related)

For keyed lookups use @ContributesIntoMap / @IntoMap with a map key (@StringKey, @ClassKey, …). Map contributions support priority for the same key; sets do not.

5. Scoping and singletons

@SingleIn(AppScope::class)
@ContributesBinding(scope = AppScope::class, binding = binding<KMPLogger>())
class DefaultKMPLogger(private val logger: Logger) : KMPLogger

6. Adding a new feature module

  1. Define API in shared/<feature>/api (interfaces the graph exposes).
  2. Implement with @ContributesBinding(AppScope::class) in impl (or in a platform-* module for platform code). Use @ContributesIntoSet when the feature needs many plugins of one type instead of a single binding.
  3. Add implementation(projects.shared.<feature>.impl) (or the platform module) to the matching source set in shared/di/build.gradle.kts.
  4. Extend BaseDependencyGraph / ObservabilityGraph with new val properties — Metro will require bindings for them at compile time. For multibindings, expose Set<T> (or declare @Multibinds(allowEmpty = true) if empty is allowed).

Do not duplicate the same binding with both @ContributesBinding and @Provides for the same type. Do not use @ContributesBinding and @ContributesIntoSet for the same “one vs many” intent on the same type without a clear design — pick one model.

For ready-to-use AI prompts that scaffold a full feature (api / spi / impl with data layer, use cases, presentation, and Metro wiring) for each provider option, see docs/prompts.

7. Where to look in this repo

Pattern Example
Graph + factory shared/di
Feature facade @ContributesBinding shared/observability/impl
Firebase SDK @Provides FirebaseSdkBindings
Platform @ContributesBinding FirebaseAnalyticsPlatform
JVM/JS/Wasm no-ops platform-observability-noop
Multibindings (@ContributesIntoSet → Set<T> fold) Not shipped in this sample (no Circuit/plugin registry yet) — follow §4 when adding feature plugins / screen registrations

Quickstart

  1. Clone the repo.
  2. Copy androidApp/google-services.json.example → androidApp/google-services.json and replace placeholders with your Firebase Android app config.
  3. Android: ./gradlew :androidApp:assembleDebug
  4. Desktop: ./gradlew :desktopApp:run
  5. iOS: See docs/TEMPLATE.md — Firebase iOS (SPM resolve + Xcode).

Optional: rename package with scripts/rename-package.sh (see TEMPLATE.md).

Build and run

Android

./gradlew :androidApp:assembleDebug

Desktop (JVM)

./gradlew :desktopApp:run

Web

Wasm (recommended):

./gradlew :webApp:wasmJsBrowserDevelopmentRun

JS (older browsers):

./gradlew :webApp:jsBrowserDevelopmentRun

iOS

Open iosApp in Xcode and run, after resolving Kotlin frameworks (see docs/TEMPLATE.md).

CI (Fastlane)

CI is orchestrated with Fastlane lanes (build/test only, no store deploy). Install once with bundle install, then run the same checks as GitHub Actions:

bundle exec fastlane ci_android
bundle exec fastlane ci_desktop
bundle exec fastlane ci_web
bundle exec fastlane ci_ios    # macOS only
bundle exec fastlane ci_all    # all platforms; skips iOS off macOS

See CONTRIBUTING.md — Fastlane CI for the lane ↔ job mapping.

Learn more

License

This project is licensed under the Apache License 2.0.

You may use, modify, and distribute this template — including in proprietary commercial applications — as long as you comply with the license (retain copyright notices, state changes where required, and include a copy of the license in distributions that ship the licensed code). No additional permission is required from the maintainer.

See LICENSE for the full legal text.

About

KMP base project with Umbrella and different options

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages