{"slug":"kmp-data-layer","title":"kmp-data-layer","summary":"Use when designing, adding or refactoring the data layer of a Kotlin Multiplatform app in commonMain — Ktor HttpClient setup, DTOs and kotlinx.serialization, repositories and mappers, a typed result/error wrapper, bearer token refresh, offline-first caching with Room 3 or SQLDeli","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-03T17:29:49.749495Z","repo":{"url":"https://github.com/Kushpawan/kmp-mobile-skills","stars":17,"forks":2,"license":"Apache-2.0","updatedAt":"2026-12-03T13:18:24Z"},"bodyHtml":"<hr>\n<h2>name: kmp-data-layer\ndescription: Use when designing, adding or refactoring the data layer of a Kotlin Multiplatform app in commonMain — Ktor HttpClient setup, DTOs and kotlinx.serialization, repositories and mappers, a typed result/error wrapper, bearer token refresh, offline-first caching with Room 3 or SQLDelight — or when debugging MissingFieldException, JsonConvertException, JsonDecodingException, 401 refresh loops, random logouts, tokens in logs, iOS-only network timeouts, or flows that stop updating in release builds.\nlicense: Apache-2.0\ncompatibility: Kotlin Multiplatform project (Android + iOS) using or adopting Ktor client 3.x (3.6 current) and kotlinx.serialization 1.7+ (1.13 current). iOS compile checks need macOS with Xcode.\nmetadata:\ncategory: data\nplatforms: android, ios</h2>\n<h1>KMP data layer</h1>\n<p>The wire is untrusted; the domain is not. Parse responses into nullable DTOs, validate and map them in\nthe data layer, and expose only non-null domain models and a typed result. One configured <code>HttpClient</code>\nis the only door to the network. When a screen must work offline, the UI observes the database, not\nthe network response.</p>\n<h2>When to use</h2>\n<ul>\n<li>Designing the remote and local data layer of a new KMP app or module.</li>\n<li>Adding a repository, mapper, error type, cache or sync path to existing shared code.</li>\n<li>Reviewing data-layer code against the failure modes in <strong>Common mistakes</strong>.</li>\n<li>Debugging: one malformed item empties a whole list; 401 loops or random logouts; tokens in\nLogcat or the Xcode console; iOS-only timeouts; a cached flow that stops updating in release.</li>\n</ul>\n<h2>When not to use</h2>\n<ul>\n<li>Adding one concrete REST endpoint end to end — use <strong>kmp-api-endpoint</strong> (it follows this skill's rules).</li>\n<li>Room setup, DAOs, migrations — <strong>kmp-room-database</strong>. Koin modules — <strong>kmp-koin-di</strong>. Token\nstorage and logout wipe — <strong>kmp-secure-storage</strong>.</li>\n</ul>\n<h2>Step 0 — Read the project first</h2>\n<pre><code>grep -rn \"HttpClient(\" --include=*.kt .                                                    # 1 client\ngrep -rnE \"sealed (class|interface) [A-Za-z]*(Result|Outcome|Either)\" --include=*.kt .    # 2 wrapper\ngrep -rnE \"DispatcherProvider|CoroutineDispatchers|Dispatchers\\.IO\" --include=*.kt .      # 3 dispatchers\ngrep -nE \"ktor|serialization|coroutines|datetime|room|sqldelight|koin|kermit|napier\" gradle/libs.versions.toml  # 4 stack + versions\nfind . -path \"*commonTest*\" -name \"*.kt\" | head -20                                       # 5 tests\n</code></pre>\n<table>\n<thead>\n<tr>\n<th>Finding</th>\n<th>Then</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>A client factory or DI-provided <code>HttpClient</code></td>\n<td>Inject it. Do not build a second client.</td>\n</tr>\n<tr>\n<td>A result wrapper (sealed type, <code>Either</code>, <code>kotlin.Result</code>) or a dispatcher provider</td>\n<td>Use it. Never add a second one.</td>\n</tr>\n<tr>\n<td>Room 2.x, SQLDelight, Realm or DataStore</td>\n<td>Follow it. New cache with no precedent: Room 3 (<code>androidx.room3</code>) via <strong>kmp-room-database</strong>.</td>\n</tr>\n<tr>\n<td>Koin, kotlin-inject, Hilt or manual DI; Kermit or Napier</td>\n<td>Wire in that idiom; route HTTP logs through that logger.</td>\n</tr>\n<tr>\n<td>An existing feature</td>\n<td>Copy its layout: where DTOs live, <code>toDomain()</code> or mapper classes, use cases or not.</td>\n</tr>\n<tr>\n<td>Ktor below 3.6.2, serialization 1.12.x, coroutines below 1.11, <code>kotlinx.datetime.Instant</code></td>\n<td>Known pitfalls and workarounds: <a href=\"references/version-notes.md\">references/version-notes.md</a>. Do not upgrade as a side effect.</td>\n</tr>\n<tr>\n<td><code>Fake*</code> classes, <code>MockEngine</code>, Turbine</td>\n<td>Write tests the same way.</td>\n</tr>\n</tbody>\n</table>\n<p>Defaults below apply only when the project has no precedent.</p>\n<h2>Workflow</h2>\n<h3>1. Lay out the layers</h3>\n<pre><code>shared/src/commonMain/kotlin/com/example/app/\n├── core/network/        HttpClient factory, AppJson, ApiResult, DataError, safeApiCall\n├── core/coroutines/     DispatcherProvider\n└── notes/\n    ├── data/            remote/ (NotesApi, KtorNotesApi, dto/), local/ (NoteEntity, NotesDao — only\n    │                    when cached), NoteMappers.kt, NotesRepositoryImpl.kt\n    └── domain/          Note.kt (non-null, no annotations), NotesRepository.kt (interface)\n</code></pre>\n<p>Dependencies point inward: <code>domain</code> imports nothing from Ktor, kotlinx.serialization or Room. Each\nfeature owns its API, DTOs and repository; shared modules hold only infrastructure. Two features\ncalling the same endpoint may each declare a DTO — duplication is cheaper than coupling. Done when\nthis prints nothing:</p>\n<pre><code>grep -rnE \"import (io\\.ktor|kotlinx\\.serialization|androidx\\.room)\" --include=*.kt $(find . -type d -name domain -path \"*commonMain*\")\n</code></pre>\n<h3>2. One HttpClient, configured once</h3>\n<ul>\n<li>Build it in core/network and provide it as a DI singleton. Never call <code>HttpClient()</code> or\n<code>install(...)</code> in feature code — a second client loses auth, timeouts and log redaction.</li>\n<li>The factory takes the <code>HttpClientEngine</code>: OkHttp on Android, Darwin on iOS, <code>MockEngine</code> in tests.</li>\n<li>It installs: <code>ContentNegotiation</code> with one shared <code>Json</code>, <code>HttpTimeout</code>, <code>Logging</code> gated by build\ntype (<code>HEADERS</code> in debug, <code>NONE</code> in release) with header sanitising, <code>defaultRequest</code> with the\nbase URL, and sets <code>expectSuccess = true</code>.</li>\n<li>Do not build it eagerly on the main thread at app start: before Ktor 3.6.0, client construction\non Android initialised SLF4J eagerly, and a start-up ANR was reported (KTOR-9834).</li>\n</ul>\n<p>Details: <a href=\"references/http-client.md\">references/http-client.md</a>. Done when exactly one production\nconstruction site exists (<strong>Verify</strong>).</p>\n<h3>3. Refresh tokens in one place</h3>\n<ul>\n<li>Ktor's <code>Auth { bearer { loadTokens; refreshTokens } }</code> on the authenticated client attaches the\ntoken, refreshes on a 401 and retries — <strong>single-flight</strong> within the client. Never copy a\n401-retry loop into repository methods.</li>\n<li>Two clients: a plain one for login and refresh, and <code>named(\"authenticated\")</code>. Refresh through the\nplain client (or <code>markAsRefreshTokenRequest()</code>), or a 401 on refresh loops.</li>\n<li><code>sendWithoutRequest { it.url.host == apiHost }</code> keeps tokens off CDNs and pre-signed URLs.</li>\n<li>Sign out only when the server rejects the refresh token, never on a timeout.</li>\n</ul>\n<p>Contracts, the refresher, logout cache clearing, Ktor 3.6 auth fixes (KTOR-9827, KTOR-9905):\n<a href=\"references/auth-refresh.md\">references/auth-refresh.md</a>.</p>\n<h3>4. Treat DTOs as untrusted input</h3>\n<pre><code>// commonMain — notes/data/remote/dto/NoteDto.kt\n@Serializable\ndata class NoteDto(\n    @SerialName(\"id\") val id: String? = null,\n    @SerialName(\"title\") val title: String? = null,\n    @SerialName(\"body\") val body: String? = null,\n    @SerialName(\"updated_at\") val updatedAt: Long? = null,\n    @SerialName(\"tags\") val tags: List&lt;String&gt;? = null,\n    @SerialName(\"visibility\") val visibility: String? = null,   // enum as String: new values must not crash old apps\n)\n\n@Serializable\ndata class NotesPageDto(@SerialName(\"items\") val items: List&lt;NoteDto&gt;? = null, @SerialName(\"next_cursor\") val nextCursor: String? = null)\n</code></pre>\n<ul>\n<li><strong>Every response field nullable, defaulting to <code>null</code>, with an explicit <code>@SerialName</code>.</strong> A\nnon-null field the server omits for one item throws <code>MissingFieldException</code> (Ktor wraps it in\n<code>JsonConvertException</code>) and fails the whole page, not just that item. <code>@SerialName</code> keeps the\nwire contract greppable.</li>\n<li>Decode server enums as <code>String?</code> and map them, or a value added server-side crashes every old install.</li>\n<li>Timestamps and ids: <code>kotlin.time.Instant</code> and <code>kotlin.uuid.Uuid</code> have stable serializers since\nkotlinx.serialization 1.12.0, but a malformed value fails the whole response. Unless the contract\nis strict, keep <code>String?</code> (or epoch <code>Long?</code>) in the DTO and parse in the mapper. Never use the\ndeprecated <code>kotlinx.datetime.Instant</code> in new code.</li>\n<li>No <code>init { require(...) }</code> in DTOs: validation belongs in the mapper, and the exception it throws\nchanged class between kotlinx.serialization 1.12 and 1.13.</li>\n<li>Request bodies you send may be non-null — you control them.</li>\n</ul>\n<h3>5. Keep domain models non-null</h3>\n<pre><code>// commonMain — notes/domain/Note.kt  (no serialization annotations)\ndata class Note(\n    val id: String, val title: String, val body: String,\n    val updatedAtEpochMillis: Long, val tags: List&lt;String&gt;, val visibility: NoteVisibility,\n)\nenum class NoteVisibility { Private, Shared, Unknown }\n</code></pre>\n<p>Nullable only where absence means something to the domain.</p>\n<h3>6. Map and validate in the data layer</h3>\n<pre><code>// commonMain — notes/data/NoteMappers.kt\ninternal fun NoteDto.toDomainOrNull(): Note? {\n    val id = id?.takeIf { it.isNotBlank() } ?: return null   // no identity: row is unusable, drop it\n    return Note(\n        id = id,\n        title = title?.trim().orEmpty(),                       // cosmetic: safe fallback\n        body = body.orEmpty(),\n        updatedAtEpochMillis = updatedAt ?: 0L,\n        tags = tags.orEmpty().filter { it.isNotBlank() },\n        visibility = when (visibility?.lowercase()) {\n            \"private\" -&gt; NoteVisibility.Private\n            \"shared\" -&gt; NoteVisibility.Shared\n            else -&gt; NoteVisibility.Unknown\n        },\n    )\n}\n\ninternal fun List&lt;NoteDto&gt;?.toDomainNotes(): List&lt;Note&gt; = orEmpty().mapNotNull { it.toDomainOrNull() }\n</code></pre>\n<p>Decide per field: <strong>drop</strong> the row when a field it cannot exist without is missing (identity,\nforeign key, payment amount); <strong>fall back</strong> when it is cosmetic. One test per rule. Log the count\nof dropped rows, never the values. Nullability never leaks past the mapper.</p>\n<h3>7. Keep the API service thin</h3>\n<pre><code>// commonMain — notes/data/remote/NotesApi.kt\ninterface NotesApi {\n    suspend fun getNotes(cursor: String?): NotesPageDto\n}\n\ninternal class KtorNotesApi(private val client: HttpClient) : NotesApi {\n    override suspend fun getNotes(cursor: String?): NotesPageDto =\n        client.get(\"notes\") { cursor?.let { parameter(\"cursor\", it) } }.body()\n}\n</code></pre>\n<p>No <code>try</code>/<code>catch</code> here, no mapping, no base URL. Paths are relative to the <code>defaultRequest</code> base\nURL, which must end with <code>/</code>; a path with a leading <code>/</code> replaces the base path (<code>/v1/</code> is lost).</p>\n<h3>8. Make the repository the error boundary</h3>\n<pre><code>// commonMain — notes/data/NotesRepositoryImpl.kt\nclass NotesRepositoryImpl(\n    private val notesApi: NotesApi,\n    private val dispatchers: DispatcherProvider,\n) : NotesRepository {\n\n    override suspend fun getNotes(cursor: String?): ApiResult&lt;NotesPage&gt; =\n        safeApiCall(dispatchers.default) {\n            val page = notesApi.getNotes(cursor)\n            NotesPage(notes = page.items.toDomainNotes(), nextCursor = page.nextCursor)\n        }\n}\n</code></pre>\n<p><code>safeApiCall</code> turns every exception into a typed <code>DataError</code> and <strong>rethrows\n<code>CancellationException</code></strong>. Ktor is main-safe, but deserialization and mapping run on the caller's\ndispatcher, so large payloads move off <code>Main</code>. Types, exception mapping and serialization-version\ntriage: <a href=\"references/api-result.md\">references/api-result.md</a>. If the project has a wrapper, map\ninto it. ViewModels see only domain types and the result type, never DTOs or Ktor exceptions.</p>\n<h3>9. Inject dispatchers</h3>\n<pre><code>// commonMain — core/coroutines/DispatcherProvider.kt\ninterface DispatcherProvider {\n    val main: CoroutineDispatcher\n    val io: CoroutineDispatcher        // Dispatchers.IO needs `import kotlinx.coroutines.IO` outside the JVM\n    val default: CoroutineDispatcher\n}\n</code></pre>\n<p>Production returns <code>Dispatchers.Main</code>/<code>IO</code>/<code>Default</code>; tests pass one\n<code>StandardTestDispatcher(testScheduler)</code> for all three. Never read the current dispatcher from the\ncontext: kotlinx.coroutines 1.11 deprecates <code>coroutineContext[CoroutineDispatcher]</code> (use\n<code>ContinuationInterceptor</code>) and flags passing a <code>Job</code> to <code>launch</code>/<code>async</code>, which breaks structured\nconcurrency.</p>\n<h3>10. Go offline-first when the screen must work without network</h3>\n<p>Default cache with no precedent: <strong>Room 3</strong> (<code>androidx.room3</code>, via <strong>kmp-room-database</strong>); keep\nRoom 2.x or SQLDelight where the project uses them.</p>\n<ul>\n<li><strong>Read:</strong> the DAO returns <code>Flow&lt;List&lt;Entity&gt;&gt;</code>; the repository maps it to domain models; the UI\nobserves only this. A read never throws and is not wrapped in the result type.</li>\n<li><strong>Refresh:</strong> a <code>suspend</code> call fetches, maps and writes in one transaction (<code>@Transaction</code> DAO\nmethod, or <code>withWriteTransaction { }</code> across DAOs in Room 3) and returns <code>ApiResult&lt;Unit&gt;</code>. Its\nresult drives only the spinner and error UI — the database write updates the screen.</li>\n<li><strong>Writes made offline:</strong> insert a pending row, then trigger a sync worker. It posts, marks the\nrow synced, or retries with backoff (network errors, 429, 5xx); any other 4xx marks it failed.</li>\n<li><strong>Never make a user gesture await the whole outbox.</strong> Trigger the sync and wait a bounded time\nfor the gesture's own row; returning \"pending\" is a valid success.</li>\n<li>Store a last-synced timestamp per cache key: \"never loaded\" is not \"loaded, empty\".</li>\n<li>Sharing a cached flow with <code>stateIn</code>/<code>shareIn</code>: use kotlinx.coroutines 1.11.0+. Earlier, an R8\noptimisation could let the sharing coroutine be garbage-collected, so minified builds stopped updating.</li>\n</ul>\n<pre><code>// commonMain — notes/data/OfflineNotesRepository.kt\nclass OfflineNotesRepository(\n    private val notesApi: NotesApi,\n    private val notesDao: NotesDao,\n    private val dispatchers: DispatcherProvider,\n) {\n    fun observeNotes(): Flow&lt;List&lt;Note&gt;&gt; = notesDao.observeAll().map { rows -&gt; rows.map { it.toDomain() } }\n    suspend fun refresh(): ApiResult&lt;Unit&gt; = safeApiCall(dispatchers.default) {\n        val notes = notesApi.getNotes(cursor = null).items.toDomainNotes()\n        notesDao.replaceAll(notes.map { it.toEntity() })   // @Transaction DAO method\n    }\n}\n</code></pre>\n<p>Clearing cached tables on logout: <strong>kmp-secure-storage</strong>.</p>\n<h3>11. Wire it</h3>\n<pre><code>// commonMain — notes/di/NotesDataModule.kt  (Koin, the default when nothing else exists)\nval notesDataModule = module {\n    single&lt;NotesApi&gt; { KtorNotesApi(client = get(named(\"authenticated\"))) }\n    singleOf(::NotesRepositoryImpl) bind NotesRepository::class\n}\n</code></pre>\n<p><code>singleOf(::X)</code> cannot pass a qualifier; use a lambda for qualified dependencies. More: <strong>kmp-koin-di</strong>.</p>\n<h3>12. Test at the seams</h3>\n<table>\n<thead>\n<tr>\n<th>Unit</th>\n<th>Test with</th>\n<th>Assert</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Mapper</td>\n<td>plain <code>commonTest</code></td>\n<td>each drop rule and each fallback</td>\n</tr>\n<tr>\n<td>API + client config</td>\n<td><code>MockEngine</code> through the real factory</td>\n<td>path, query, headers, body; 401 → refresh → retry</td>\n</tr>\n<tr>\n<td>Repository</td>\n<td>hand-written <code>FakeNotesApi</code></td>\n<td>success, every <code>DataError</code>, cancellation propagates</td>\n</tr>\n<tr>\n<td>ViewModel</td>\n<td>fake repository + test dispatcher</td>\n<td>state via <code>_state.update { }</code>, one-shot events</td>\n</tr>\n</tbody>\n</table>\n<p>Use the production <code>AppJson</code> in tests. Recipes: <a href=\"references/testing.md\">references/testing.md</a>.</p>\n<h2>Quick reference</h2>\n<table>\n<thead>\n<tr>\n<th>Concern</th>\n<th>Default</th>\n<th>Rule</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>JSON</td>\n<td>one <code>Json { ignoreUnknownKeys = true; explicitNulls = false }</code></td>\n<td>shared by client and tests</td>\n</tr>\n<tr>\n<td>DTO field</td>\n<td><code>@SerialName(\"x\") val x: T? = null</code></td>\n<td>every response field; no <code>init</code> validation</td>\n</tr>\n<tr>\n<td>Errors</td>\n<td><code>ApiResult&lt;T&gt;</code> + <code>DataError</code></td>\n<td>mapped in the repository; <code>CancellationException</code> rethrown</td>\n</tr>\n<tr>\n<td>Timeouts</td>\n<td><code>HttpTimeout</code> request + socket</td>\n<td>Darwin ignores <code>connectTimeoutMillis</code></td>\n</tr>\n<tr>\n<td>Logging</td>\n<td><code>HEADERS</code> in debug, <code>NONE</code> in release</td>\n<td><code>sanitizeHeader</code> for <code>Authorization</code>, <code>Cookie</code></td>\n</tr>\n<tr>\n<td>Auth</td>\n<td><code>Auth { bearer { } }</code> on the authenticated client</td>\n<td>single-flight refresh; tokens only to your host</td>\n</tr>\n<tr>\n<td>Time, ids</td>\n<td><code>kotlin.time.Instant</code>, <code>kotlin.uuid.Uuid</code></td>\n<td>parse in the mapper unless the contract is strict</td>\n</tr>\n<tr>\n<td>Offline</td>\n<td>Room 3 DAO <code>Flow</code> is the source of truth</td>\n<td>network calls write to the DB</td>\n</tr>\n</tbody>\n</table>\n<h2>Verify</h2>\n<p>Run what applies; report each line as <code>PASS</code>, <code>FAIL</code> or <code>NOT RUN</code> (with the reason). Never report\na check as passed that you did not run. Module and task names vary — read <code>settings.gradle.kts</code>\nand run <code>./gradlew :shared:tasks --all | grep -i test</code> when unsure.</p>\n<pre><code>./gradlew :shared:allTests                         # common, Android host and iOS simulator tests\n./gradlew :shared:compileKotlinIosSimulatorArm64   # commonMain compiles for iOS\n./gradlew :composeApp:assembleDebug                # Android app still builds\n</code></pre>\n<p>Static checks (each should print nothing, or only lines you have reviewed):</p>\n<pre><code>grep -rn \"HttpClient(\" --include=*.kt . | grep -viE \"test|mock\"               # one production site only\ngrep -rnE \"val [A-Za-z0-9_]+: [^?=]+(,|$)\" --include=*Dto.kt .                # non-null response DTO fields\ngrep -rnE \"println\\(|NSLog\\(|Log\\.[dviwe]\\(\" --include=*.kt . | grep -v Test   # bypasses log redaction\ngrep -rn \"install(\" --include=*.kt . | grep -v \"core/network\" | grep -viE \"test\" # plugins outside the network module\ngrep -rnE \"import kotlinx\\.datetime\\.(Instant|Clock)$|\\[CoroutineDispatcher\\]\" --include=*.kt .   # deprecated APIs\n</code></pre>\n<h2>Common mistakes</h2>\n<table>\n<thead>\n<tr>\n<th>Mistake</th>\n<th>Why it bites</th>\n<th>Fix</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Non-null DTO field without default</td>\n<td>One item missing it fails the whole response with <code>MissingFieldException</code> / <code>JsonConvertException</code></td>\n<td>Nullable, <code>= null</code>, map in the repository</td>\n</tr>\n<tr>\n<td><code>catch (e: Exception)</code> or <code>runCatching</code> around a suspend call</td>\n<td>Swallows <code>CancellationException</code>; cancelled screens keep working and leak</td>\n<td>Catch <code>CancellationException</code> first and rethrow (see <code>safeApiCall</code>)</td>\n</tr>\n<tr>\n<td><code>expectSuccess = false</code> then <code>.body&lt;T&gt;()</code></td>\n<td>A 404 or 500 error envelope is parsed as <code>T</code> and surfaces as a misleading parse error</td>\n<td><code>expectSuccess = true</code>; map <code>ResponseException</code> by status</td>\n</tr>\n<tr>\n<td><code>HttpClient()</code> inside a feature or per call</td>\n<td>Loses auth, timeouts, redaction; new connection pool each time</td>\n<td>Inject the shared client</td>\n</tr>\n<tr>\n<td><code>LogLevel.ALL</code> / <code>BODY</code> in release</td>\n<td>Bodies with passwords and tokens reach device logs; <code>sanitizeHeader</code> does not touch bodies</td>\n<td><code>HEADERS</code> in debug only, <code>NONE</code> in release</td>\n</tr>\n<tr>\n<td>Refresh through the <code>Auth</code> plugin, token sent to every host, or sign-out on an offline refresh</td>\n<td>Refresh loops, tokens on CDNs, random logouts</td>\n<td>Plain client for refresh, <code>sendWithoutRequest</code>, sign out only on rejection — <a href=\"references/auth-refresh.md\">references/auth-refresh.md</a></td>\n</tr>\n<tr>\n<td>Triaging a parse failure without the serialization version</td>\n<td>1.12.x wraps decoding failures in <code>JsonDecodingException</code>; 1.13.0 reverted it</td>\n<td>Name the version; catch <code>SerializationException</code> + <code>ContentConvertException</code></td>\n</tr>\n<tr>\n<td>Base URL without trailing <code>/</code>, or path with leading <code>/</code></td>\n<td><code>/v1</code> is dropped and requests hit the wrong path</td>\n<td><code>https://api.example.com/v1/</code> + <code>get(\"notes\")</code></td>\n</tr>\n<tr>\n<td><code>explicitNulls = false</code> with PATCH</td>\n<td>Null fields are omitted, so \"clear this field\" never reaches the server</td>\n<td>Send an explicit request DTO or a <code>JsonObject</code> for clears</td>\n</tr>\n<tr>\n<td><code>Dispatchers.IO</code> hard-coded in a repository</td>\n<td>Tests race real threads and flake</td>\n<td>Inject <code>DispatcherProvider</code></td>\n</tr>\n<tr>\n<td>UI binds to the network response in an offline app</td>\n<td>Data disappears offline and after process death</td>\n<td>Observe the DAO <code>Flow</code>; network writes into it</td>\n</tr>\n</tbody>\n</table>\n<h2>Related skills</h2>\n<ul>\n<li><strong>kmp-api-endpoint</strong> — one endpoint end to end using these rules.</li>\n<li><strong>kmp-room-database</strong> — Room 3 setup, DAOs, transactions, migrations, iOS linking.</li>\n<li><strong>kmp-koin-di</strong> — modules, qualifiers, bootstrap order. <strong>kmp-secure-storage</strong> — tokens, logout wipe.</li>\n<li>Ktor client: <a href=\"https://ktor.io/docs/client-create-multiplatform-application.html\">https://ktor.io/docs/client-create-multiplatform-application.html</a>, bearer auth:\n<a href=\"https://ktor.io/docs/client-bearer-auth.html\">https://ktor.io/docs/client-bearer-auth.html</a></li>\n<li>Compose-side state and ViewModels: <a href=\"https://github.com/Meet-Miyani/compose-skill\">https://github.com/Meet-Miyani/compose-skill</a></li>\n<li>Android-only data patterns: <a href=\"https://github.com/rcosteira79/android-skills\">https://github.com/rcosteira79/android-skills</a></li>\n</ul>\n","files":[{"path":"references/api-result.md","sizeBytes":8677,"isText":true},{"path":"references/auth-refresh.md","sizeBytes":8535,"isText":true},{"path":"references/http-client.md","sizeBytes":8559,"isText":true},{"path":"references/testing.md","sizeBytes":6325,"isText":true},{"path":"references/version-notes.md","sizeBytes":6377,"isText":true},{"path":"SKILL.md","sizeBytes":19185,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-03T17:30:11.272202Z","sha256":"8D8CAF5749506584570CF709C3FF201864909F58D0EFD7AA8B4DDA6BFA8F3EEA","sizeBytes":23075},"review":null,"source":{"repositoryUrl":"https://github.com/Kushpawan/kmp-mobile-skills","path":"skills/kmp-data-layer","license":"Apache-2.0","commit":"c04c11f696aa7a0f3c67761e5e48a7fd8201efa9","subtreeSha":"1F5EA9E49A5A1501A3880D389B4F23A7EE0977AF5288C687C241F79B280D1EB1","lastSyncedAt":"2026-12-03T17:29:47.313948Z"},"reviewedAt":"2026-12-03T17:31:14.65604Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/Kushpawan/kmp-mobile-skills/tree/main/skills/kmp-data-layer"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install kushpawan-kmp-mobile-skills@llmmart"},{"target":"git","command":"git clone https://github.com/Kushpawan/kmp-mobile-skills.git"}]}