patterns.html
docs/patterns.html
1<!doctype html>2<html lang="en">3<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width, initial-scale=1">6 <meta name="description" content="Reusable Kotlin Multiplatform patterns drawn from Yokan: expect/actual, platform engines, Room, MVI, coroutines, and tests.">7 <meta name="theme-color" content="#172033">8 <title>Patterns · Yokan KMP Field Guide</title>9 <link rel="icon" href="./assets/mark.svg" type="image/svg+xml">10 <link rel="stylesheet" href="./assets/styles.css">11 <script>try{const t=localStorage.getItem('yokan-docs-theme');document.documentElement.dataset.theme=t||(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch{}</script>12 <script defer src="./assets/app.js"></script>13</head>14<body data-page="patterns">15 <a class="skip-link" href="#main-content">Skip to content</a>16 <header data-site-header></header>1718 <div class="page-shell">19 <aside class="side-nav" aria-label="Guide chapters">20 <span class="nav-label">Field guide</span>21 <ul>22 <li><a href="./getting-started.html">01 · Get started</a></li>23 <li><a href="./architecture.html">02 · Architecture</a></li>24 <li><a href="./patterns.html" aria-current="page">03 · Patterns</a></li>25 </ul>26 </aside>2728 <main id="main-content" class="page-main">29 <header class="chapter-header">30 <nav class="breadcrumbs" aria-label="Breadcrumb"><a href="./index.html">Field guide</a><span>/</span><span>Patterns</span></nav>31 <h1>Reuse the seams, not the app.</h1>32 <p>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.</p>33 <div class="chapter-meta"><span class="pill">30–40 minutes</span><span class="pill">Reference chapter</span><span class="pill">Copy the decisions</span></div>34 </header>3536 <section class="doc-section" aria-labelledby="choose-boundary">37 <h2 id="choose-boundary">Choose the smallest honest boundary</h2>38 <p>KMP gives you several ways to connect common and platform code. Use the least powerful mechanism that expresses the requirement.</p>39 <table class="comparison">40 <thead><tr><th>Mechanism</th><th>Use it when</th><th>Yokan example</th></tr></thead>41 <tbody>42 <tr><td>Portable library</td><td>A maintained multiplatform implementation already exists.</td><td>Ktor, coroutines, serialization, Room, Coil</td></tr>43 <tr><td>Common interface</td><td>Behavior has multiple implementations and should be injectable or faked.</td><td><code>HttpService</code>, <code>YokanDatabase</code></td></tr>44 <tr><td>expect / actual factory</td><td>Common code needs the platform to construct or invoke an OS capability.</td><td><code>createPlatformHttpService()</code>, <code>pickFile()</code></td></tr>45 <tr><td>Native host bridge</td><td>The platform owns lifecycle or must embed shared UI.</td><td>SwiftUI → <code>MainViewController()</code></td></tr>46 </tbody>47 </table>48 <div class="callout warning">49 <strong>Avoid platform-shaped common APIs.</strong>50 <p>If a common contract mentions <code>Activity</code>, <code>UIViewController</code>, or <code>java.io.File</code>, the boundary is leaking. Pass portable values such as bytes, URLs, paths, IDs, and domain models instead.</p>51 </div>52 </section>5354 <section class="doc-section" aria-labelledby="expect-actual">55 <h2 id="expect-actual">Pattern: expect/actual capability</h2>56 <p>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.</p>57 <div class="code-block">58 <div class="code-label"><span>commonMain/ui/screens/reader/ImageSharing.kt</span></div>59 <pre><code>expect fun shareImage(60 bytes: ByteArray,61 fileName: String,62 mimeType: String,63): Boolean</code></pre>64 </div>65 <div class="code-block">66 <div class="code-label"><span>androidMain/ui/screens/reader/ImageSharing.android.kt</span></div>67 <pre><code>actual fun shareImage(68 bytes: ByteArray,69 fileName: String,70 mimeType: String,71): Boolean {72 // Write an app-private cache file.73 // Expose it through FileProvider.74 // Launch Intent.ACTION_SEND with a content URI.75}</code></pre>76 </div>77 <h3 id="capability-checklist">Capability checklist</h3>78 <ol>79 <li>Describe the user-level capability in portable terms.</li>80 <li>Declare the narrowest common function or factory.</li>81 <li>Add an <code>actual</code> for every configured target—unsupported behavior must be explicit.</li>82 <li>Keep OS imports in target source sets.</li>83 <li>Compile all targets after changing the signature.</li>84 </ol>85 <div class="callout">86 <strong>When an interface is better</strong>87 <p>Use an interface when implementations carry state, need lifecycle management, or should be replaced in tests. Yokan uses expect/actual to create <code>HttpService</code>, then passes the interface through the shared service graph.</p>88 </div>89 </section>9091 <section class="doc-section" aria-labelledby="platform-engines">92 <h2 id="platform-engines">Pattern: shared client, target engine</h2>93 <p>Ktor's request API is shared, but transport engines integrate with each target's networking stack. The Gradle source-set dependency and the matching <code>actual</code> should tell the same story.</p>94 <div class="code-block">95 <div class="code-label"><span>composeApp/build.gradle.kts</span></div>96 <pre><code>commonMain.dependencies {97 implementation(libs.ktor.client.core)98}99100androidMain.dependencies {101 implementation(libs.ktor.client.okhttp)102}103104desktopMain.dependencies {105 implementation(libs.ktor.client.okhttp)106}107108iosMain.dependencies {109 implementation(libs.ktor.client.darwin)110}</code></pre>111 </div>112 <div class="code-block">113 <div class="code-label"><span>matching factories</span></div>114 <pre><code>// JVM targets115actual fun createPlatformHttpService() =116 KtorHttpService(OkHttp.create())117118// Apple targets119actual fun createPlatformHttpService() =120 KtorHttpService(Darwin.create())</code></pre>121 </div>122 <p>This pattern also appears in database drivers, image loading, and JavaScript runtimes: share the contract and orchestration; select the engine near the target.</p>123 </section>124125 <section class="doc-section" aria-labelledby="intermediate-source-sets">126 <h2 id="intermediate-source-sets">Pattern: intermediate source sets</h2>127 <p>Android and desktop can both use JVM libraries, while iOS cannot. Duplicating JVM code in two target folders hides that commonality; putting it in <code>commonMain</code> makes it uncompilable. An intermediate source set is the precise answer.</p>128 <div class="code-block">129 <div class="code-label"><span>composeApp/build.gradle.kts</span></div>130 <pre><code>kotlin {131 applyDefaultHierarchyTemplate {132 common {133 group("nonWeb") {134 group("jvmCommon") {135 withAndroidTarget()136 withJvm()137 }138 group("ios")139 }140 }141 }142 sourceSets {143 val jvmCommonMain by creating {144 dependencies {145 implementation(libs.ktor.client.okhttp)146 }147 }148 }149}</code></pre>150 </div>151 <div class="file-tree"><b>commonMain</b>152└── <em>jvmCommonMain</em> ← JVM-capable implementation153 ├── androidMain154 └── desktopMain155156<b>commonMain</b>157└── <em>platformWebViewMain</em> ← shared WebView library surface158 ├── androidMain159 └── iosMain</div>160 <p>Name intermediate source sets after a capability or platform family. Avoid vague buckets such as <code>sharedMain</code>; every source set is shared by something.</p>161 </section>162163 <section class="doc-section" aria-labelledby="room-kmp">164 <h2 id="room-kmp">Pattern: shared Room schema, platform path</h2>165 <p>Room KMP lets Yokan keep entities, DAOs, schema version, and row adapters in shared Kotlin. Platform builders decide where the SQLite file lives.</p>166 <h3 id="room-processor">Configure code generation per target</h3>167 <div class="code-block">168 <div class="code-label"><span>composeApp/build.gradle.kts</span></div>169 <pre><code>dependencies {170 add("kspAndroid", libs.room.compiler)171 add("kspDesktop", libs.room.compiler)172 add("kspIosArm64", libs.room.compiler)173 add("kspIosSimulatorArm64", libs.room.compiler)174}</code></pre>175 </div>176 <h3 id="room-builder">Build with a target-owned location</h3>177 <div class="code-block">178 <div class="code-label"><span>iosMain/database/room/YokanRoomDatabase.ios.kt</span></div>179 <pre><code>actual fun createYokanRoomDatabase(): YokanRoomDatabase {180 val dbUrl = documentsDirectory.URLByAppendingPathComponent(181 "yokan-room.db"182 )183 return Room.databaseBuilder<YokanRoomDatabase>(name = dbUrl.path!!)184 .setDriver(BundledSQLiteDriver())185 .setQueryCoroutineContext(Dispatchers.Default)186 .build()187}</code></pre>188 </div>189 <ul class="checklist">190 <li>Keep schema snapshots in version control.</li>191 <li>Apply the Room compiler to every target that creates the database.</li>192 <li>Use a bundled driver when consistent SQLite behavior matters across OS versions.</li>193 <li>Test mapping and repository behavior against the common database contract.</li>194 </ul>195 </section>196197 <section class="doc-section" aria-labelledby="shared-mvi">198 <h2 id="shared-mvi">Pattern: shared MVI state</h2>199 <p>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.</p>200 <div class="code-block">201 <div class="code-label"><span>commonMain/ui/screens/reader/ReaderViewModel.kt + ReaderRoute.kt</span></div>202 <pre><code>class ReaderViewModel(/* repository, settings, libraryIndex, … */) : ViewModel() {203 private val _state = MutableStateFlow(ReaderState(/* … */))204 val state: StateFlow<ReaderState> = _state.asStateFlow()205206 private val _effects = Channel<ReaderEffect>(Channel.BUFFERED)207 val effects: Flow<ReaderEffect> = _effects.receiveAsFlow()208209 fun onEvent(event: ReaderEvent) { when (event) { /* exhaustive */ } }210}211212// Route adapter: the only place that reads YokanRuntime. viewModel {} is scoped to213// this back-stack entry's ViewModelStore and cleared when the entry is popped.214val vm = viewModel { ReaderViewModel(manga, chapter, YokanRuntime.repository, YokanRuntime.settings, YokanRuntime.libraryIndex) }215val state by vm.state.collectAsStateWithLifecycle()</code></pre>216 </div>217 <h3 id="state-event-effect">State, event, or effect?</h3>218 <table class="comparison">219 <thead><tr><th>Kind</th><th>Question</th><th>Example</th></tr></thead>220 <tbody>221 <tr><td>State</td><td>Should recomposition or restoration see this value?</td><td>Current page, loading status, visible chrome</td></tr>222 <tr><td>Event</td><td>What did the user or system ask the screen to do?</td><td>Next page, retry, change reader mode</td></tr>223 <tr><td>Effect</td><td>Should this happen once outside normal rendering?</td><td>Exit screen, show message, toggle native fullscreen</td></tr>224 </tbody>225 </table>226 <p>Keep the event handler exhaustive. Adding a sealed event then forces every handler to acknowledge it at compile time.</p>227 </section>228229 <section class="doc-section" aria-labelledby="coroutine-ownership">230 <h2 id="coroutine-ownership">Pattern: coroutine ownership</h2>231 <p>Cross-platform concurrency is easiest to reason about when scopes belong to lifecycle owners and dispatchers describe the work, not the platform.</p>232 <ul>233 <li><strong>ViewModel work:</strong> use <code>viewModelScope</code>; cancellation follows the navigation entry. Take the off-main dispatcher as a constructor parameter (<code>workDispatcher = Dispatchers.Default</code>) so tests keep every hop on the test scheduler.</li>234 <li><strong>Composition scopes:</strong> <code>rememberCoroutineScope</code> is for scroll/pager animation and platform pickers, never for service calls.</li>235 <li><strong>Application startup:</strong> use one supervised application scope owned by the runtime.</li>236 <li><strong>Database queries:</strong> set a query coroutine context when building Room.</li>237 <li><strong>Blocking or native initialization:</strong> move it off the Compose main thread before creating UI-visible state.</li>238 <li><strong>One-shot UI work:</strong> emit an effect; let the composition invoke the platform capability.</li>239 </ul>240 <div class="callout warning">241 <strong>Do not assume JVM threading rules on Kotlin/Native.</strong>242 <p>Prefer coroutine and library abstractions that explicitly support KMP. Compile and run the iOS target when changing concurrency, object lifetime, or native interop.</p>243 </div>244 </section>245246 <section class="doc-section" aria-labelledby="test-shared-boundaries">247 <h2 id="test-shared-boundaries">Pattern: test shared boundaries with fakes</h2>248 <p>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.</p>249 <div class="code-block">250 <div class="code-label"><span>commonTest/services/LnReaderExtensionRuntimeServiceTest.kt</span></div>251 <pre><code>@Test252fun popularReturnsMappedItems() = runTest {253 val service = LnReaderExtensionRuntimeService(254 source = source,255 http = FakeHttpService(),256 engineFactory = { FakeEngine() },257 )258259 val listing = service.popular(1)260261 assertEquals(2, listing.items.size)262 assertEquals("Test One", listing.items.first().title)263}</code></pre>264 </div>265 <p>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.</p>266 </section>267268 <section class="doc-section" aria-labelledby="add-capability-recipe">269 <h2 id="add-capability-recipe">Recipe: add a platform capability</h2>270 <ol>271 <li>Write the behavior from the shared caller's point of view.</li>272 <li>Check whether an existing multiplatform dependency already solves it.</li>273 <li>Define a portable interface or small expect function in <code>commonMain</code>.</li>274 <li>Implement every configured target. Return an honest unsupported result when a platform cannot provide it.</li>275 <li>Wire it through <code>ServiceRegistry</code>/<code>YokanRuntime</code> and pass it into ViewModels from route adapters; do not construct competing service graphs in screens.</li>276 <li>Add a common test for shared orchestration and a target smoke test for the native boundary.</li>277 <li>Compile Android, desktop, and iOS before considering the signature stable.</li>278 </ol>279 <div class="callout kotlin">280 <strong>Concrete exercise</strong>281 <p>Trace <code>pickFile()</code> 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.</p>282 </div>283 </section>284285 <section class="doc-section" aria-labelledby="continue-learning">286 <h2 id="continue-learning">Continue with primary references</h2>287 <ul>288 <li><a href="https://kotlinlang.org/docs/multiplatform.html">Kotlin Multiplatform documentation</a> — language, targets, source sets, and expect/actual.</li>289 <li><a href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-multiplatform.html">Compose Multiplatform documentation</a> — shared UI and platform setup.</li>290 <li><a href="https://ktor.io/docs/client-create-multiplatform-application.html">Ktor multiplatform client guide</a> — common client configuration and target engines.</li>291 <li><a href="https://developer.android.com/kotlin/multiplatform/room">Room for Kotlin Multiplatform</a> — database configuration and builders.</li>292 <li><a href="./MPV_INTEGRATION.md">Yokan MPV integration notes</a> — a deeper example of native media integration.</li>293 </ul>294 </section>295296 <nav class="next-page" aria-label="Chapter navigation">297 <a href="./architecture.html"><small>Previous</small><strong>Trace the architecture</strong></a>298 <a href="https://codeberg.org/FriedCutlet/yokan"><small>Continue</small><strong>Explore Yokan source</strong></a>299 </nav>300 </main>301302 <aside class="on-this-page" data-toc aria-label="On this page"></aside>303 </div>304305 <footer data-site-footer></footer>306</body>307</html>308