Reuse the seams, not the app.

These patterns scale beyond Yokan because they make ownership visible: shared behavior in common code, honest platform capabilities at the edge, and testable boundaries between them.

30–40 minutesReference chapterCopy the decisions

Choose the smallest honest boundary

KMP gives you several ways to connect common and platform code. Use the least powerful mechanism that expresses the requirement.

MechanismUse it whenYokan example
Portable libraryA maintained multiplatform implementation already exists.Ktor, coroutines, serialization, Room, Coil
Common interfaceBehavior has multiple implementations and should be injectable or faked.HttpService, YokanDatabase
expect / actual factoryCommon code needs the platform to construct or invoke an OS capability.createPlatformHttpService(), pickFile()
Native host bridgeThe platform owns lifecycle or must embed shared UI.SwiftUI → MainViewController()
Avoid platform-shaped common APIs.

If a common contract mentions Activity, UIViewController, or java.io.File, the boundary is leaking. Pass portable values such as bytes, URLs, paths, IDs, and domain models instead.

Pattern: expect/actual capability

Yokan's image-sharing seam accepts bytes and metadata. Common UI can request a share without learning about Android intents, desktop temporary files, or iOS activity controllers.

commonMain/ui/screens/reader/ImageSharing.kt
expect fun shareImage(
    bytes: ByteArray,
    fileName: String,
    mimeType: String,
): Boolean
androidMain/ui/screens/reader/ImageSharing.android.kt
actual fun shareImage(
    bytes: ByteArray,
    fileName: String,
    mimeType: String,
): Boolean {
    // Write an app-private cache file.
    // Expose it through FileProvider.
    // Launch Intent.ACTION_SEND with a content URI.
}

Capability checklist

  1. Describe the user-level capability in portable terms.
  2. Declare the narrowest common function or factory.
  3. Add an actual for every configured target—unsupported behavior must be explicit.
  4. Keep OS imports in target source sets.
  5. Compile all targets after changing the signature.
When an interface is better

Use an interface when implementations carry state, need lifecycle management, or should be replaced in tests. Yokan uses expect/actual to create HttpService, then passes the interface through the shared service graph.

Pattern: shared client, target engine

Ktor's request API is shared, but transport engines integrate with each target's networking stack. The Gradle source-set dependency and the matching actual should tell the same story.

composeApp/build.gradle.kts
commonMain.dependencies {
    implementation(libs.ktor.client.core)
}

androidMain.dependencies {
    implementation(libs.ktor.client.okhttp)
}

desktopMain.dependencies {
    implementation(libs.ktor.client.okhttp)
}

iosMain.dependencies {
    implementation(libs.ktor.client.darwin)
}
matching factories
// JVM targets
actual fun createPlatformHttpService() =
    KtorHttpService(OkHttp.create())

// Apple targets
actual fun createPlatformHttpService() =
    KtorHttpService(Darwin.create())

This pattern also appears in database drivers, image loading, and JavaScript runtimes: share the contract and orchestration; select the engine near the target.

Pattern: intermediate source sets

Android and desktop can both use JVM libraries, while iOS cannot. Duplicating JVM code in two target folders hides that commonality; putting it in commonMain makes it uncompilable. An intermediate source set is the precise answer.

composeApp/build.gradle.kts
kotlin {
    applyDefaultHierarchyTemplate {
        common {
            group("nonWeb") {
                group("jvmCommon") {
                    withAndroidTarget()
                    withJvm()
                }
                group("ios")
            }
        }
    }
    sourceSets {
        val jvmCommonMain by creating {
            dependencies {
                implementation(libs.ktor.client.okhttp)
            }
        }
    }
}
commonMain └── jvmCommonMain ← JVM-capable implementation ├── androidMain └── desktopMain commonMain └── platformWebViewMain ← shared WebView library surface ├── androidMain └── iosMain

Name intermediate source sets after a capability or platform family. Avoid vague buckets such as sharedMain; every source set is shared by something.

Pattern: shared Room schema, platform path

Room KMP lets Yokan keep entities, DAOs, schema version, and row adapters in shared Kotlin. Platform builders decide where the SQLite file lives.

Configure code generation per target

composeApp/build.gradle.kts
dependencies {
    add("kspAndroid", libs.room.compiler)
    add("kspDesktop", libs.room.compiler)
    add("kspIosArm64", libs.room.compiler)
    add("kspIosSimulatorArm64", libs.room.compiler)
}

Build with a target-owned location

iosMain/database/room/YokanRoomDatabase.ios.kt
actual fun createYokanRoomDatabase(): YokanRoomDatabase {
    val dbUrl = documentsDirectory.URLByAppendingPathComponent(
        "yokan-room.db"
    )
    return Room.databaseBuilder<YokanRoomDatabase>(name = dbUrl.path!!)
        .setDriver(BundledSQLiteDriver())
        .setQueryCoroutineContext(Dispatchers.Default)
        .build()
}
  • Keep schema snapshots in version control.
  • Apply the Room compiler to every target that creates the database.
  • Use a bundled driver when consistent SQLite behavior matters across OS versions.
  • Test mapping and repository behavior against the common database contract.

Pattern: shared MVI state

A screen contract gives shared UI and tests a stable language. Yokan separates durable render state from user intents and one-shot effects, and scopes the owner to the navigation entry that shows it.

commonMain/ui/screens/reader/ReaderViewModel.kt + ReaderRoute.kt
class ReaderViewModel(/* repository, settings, libraryIndex, … */) : ViewModel() {
    private val _state = MutableStateFlow(ReaderState(/* … */))
    val state: StateFlow<ReaderState> = _state.asStateFlow()

    private val _effects = Channel<ReaderEffect>(Channel.BUFFERED)
    val effects: Flow<ReaderEffect> = _effects.receiveAsFlow()

    fun onEvent(event: ReaderEvent) { when (event) { /* exhaustive */ } }
}

// Route adapter: the only place that reads YokanRuntime. viewModel {} is scoped to
// this back-stack entry's ViewModelStore and cleared when the entry is popped.
val vm = viewModel { ReaderViewModel(manga, chapter, YokanRuntime.repository, YokanRuntime.settings, YokanRuntime.libraryIndex) }
val state by vm.state.collectAsStateWithLifecycle()

State, event, or effect?

KindQuestionExample
StateShould recomposition or restoration see this value?Current page, loading status, visible chrome
EventWhat did the user or system ask the screen to do?Next page, retry, change reader mode
EffectShould this happen once outside normal rendering?Exit screen, show message, toggle native fullscreen

Keep the event handler exhaustive. Adding a sealed event then forces every handler to acknowledge it at compile time.

Pattern: coroutine ownership

Cross-platform concurrency is easiest to reason about when scopes belong to lifecycle owners and dispatchers describe the work, not the platform.

  • ViewModel work: use viewModelScope; cancellation follows the navigation entry. Take the off-main dispatcher as a constructor parameter (workDispatcher = Dispatchers.Default) so tests keep every hop on the test scheduler.
  • Composition scopes: rememberCoroutineScope is for scroll/pager animation and platform pickers, never for service calls.
  • Application startup: use one supervised application scope owned by the runtime.
  • Database queries: set a query coroutine context when building Room.
  • Blocking or native initialization: move it off the Compose main thread before creating UI-visible state.
  • One-shot UI work: emit an effect; let the composition invoke the platform capability.
Do not assume JVM threading rules on Kotlin/Native.

Prefer coroutine and library abstractions that explicitly support KMP. Compile and run the iOS target when changing concurrency, object lifetime, or native interop.

Pattern: test shared boundaries with fakes

Yokan's service tests inject a fake JavaScript engine and fake HTTP service into common code. The test checks behavior without booting a WebView, network engine, or native host.

commonTest/services/LnReaderExtensionRuntimeServiceTest.kt
@Test
fun popularReturnsMappedItems() = runTest {
    val service = LnReaderExtensionRuntimeService(
        source = source,
        http = FakeHttpService(),
        engineFactory = { FakeEngine() },
    )

    val listing = service.popular(1)

    assertEquals(2, listing.items.size)
    assertEquals("Test One", listing.items.first().title)
}

Good common tests defend portable contracts: mapping, state transitions, boundaries, errors, and ordering. Platform tests are still necessary for intents, file permissions, native frameworks, and UI behavior.

Recipe: add a platform capability

  1. Write the behavior from the shared caller's point of view.
  2. Check whether an existing multiplatform dependency already solves it.
  3. Define a portable interface or small expect function in commonMain.
  4. Implement every configured target. Return an honest unsupported result when a platform cannot provide it.
  5. Wire it through ServiceRegistry/YokanRuntime and pass it into ViewModels from route adapters; do not construct competing service graphs in screens.
  6. Add a common test for shared orchestration and a target smoke test for the native boundary.
  7. Compile Android, desktop, and iOS before considering the signature stable.
Concrete exercise

Trace pickFile() from its expect declaration into Android's activity-result launcher, desktop's file chooser, and iOS's document picker. List which concerns remain shared and which must stay native.

Continue with primary references