Sharing networking and data layers
Why it matters
- Without a shared data layer you maintain two API clients, two serialization configs, and two error-handling paths. Bugs diverge silently and one platform regresses while the other stays green.
- Interviewers for Kotlin Multiplatform roles ask how you structure the data layer. A strong answer covers Ktor with
kotlinx.serialization, a KMP database (SQLDelight or Room), a DI approach such as Koin, and where the platform boundary sits. - The platform boundary is smaller than most teams expect: the HTTP engine and the database driver differ. Models, repositories, coroutines, and serialization live in
commonMain. - Referencing
ContextincommonMainfails at compile time, but configuration that differs per platform (timeouts,Jsonsettings, missing plugins) compiles fine and fails at runtime on only one platform.
The simple explanation
- A restaurant chain has one recipe book (
commonMain) used by every location. - Each location has a different stove: gas in one city, induction in another (
OkHttpon Android,Darwinon iOS). - The chef follows the same recipe regardless of stove type (
KtorApiClientis platform-agnostic). - A kitchen manager (Koin) hands each chef the correct stove at startup.
- The finished dish (
Usermodel) looks identical in every location.
How do you share networking and a database across Android and iOS in Kotlin Multiplatform? Put models, the Ktor HttpClient configuration, repositories, and the database schema in commonMain. Only the HTTP engine and the database driver are platform-specific.
Networking. Ktor's HttpClient is multiplatform. The platform-specific piece is the engine: OkHttp on Android, Darwin (built on URLSession) on iOS. If you call HttpClient { } without an engine, Ktor picks the engine artifact on each platform's classpath. To make the choice explicit, declare expect fun createEngine(): HttpClientEngine in commonMain with actual functions returning OkHttp.create() and Darwin.create(). ContentNegotiation, the shared Json instance, HttpTimeout, retries, and logging stay in commonMain.
Data storage. SQLDelight generates type-safe Kotlin APIs from .sq files in commonMain. Each platform supplies an SqlDriver: AndroidSqliteDriver (needs a Context) on Android, NativeSqliteDriver on iOS. Room supports KMP since 2.7, which suits teams that already know Room. For key-value settings, DataStore Preferences also supports KMP.
Wiring. Hilt is Android-only, so KMP projects commonly use Koin (kotlin-inject or manual constructor injection also work). A shared module in commonMain declares the HttpClient and repositories; a small platform module supplies things that need platform types, such as the Android SqlDriver that needs a Context.
| Layer | commonMain | androidMain | iosMain |
|---|---|---|---|
| HTTP engine | expect fun createEngine() | OkHttp.create() | Darwin.create() |
| DB driver | SqlDriver from DI | AndroidSqliteDriver | NativeSqliteDriver |
| Models / repos | shared | — | — |
| DI | shared Koin module | platform module | platform module |
Prefer interfaces plus DI over expect/actual classes. expect/actual functions and properties are stable; expect/actual classes are still Beta in Kotlin 2.x.
Notes
- In a KMP data layer the platform-specific pieces are the Ktor engine and the database driver. Models, repositories, coroutines, and serialization live in
commonMain. expect fun createEngine(): HttpClientEngineis a minimal boundary:OkHttp.create()inandroidMain,Darwin.create()iniosMain.expect/actualis resolved at compile time per target, not by Koin at runtime.- Koin is a common DI choice in KMP because Hilt is Android-only. A shared
moduleincommonMainwires theHttpClientand repositories; platform modules addContext-dependent pieces. - SQLDelight generates Kotlin from
.sqfiles. Each platform supplies anSqlDriver:AndroidSqliteDrivervsNativeSqliteDriver. Room also supports Kotlin Multiplatform since 2.7. kotlinx.serializationwith@Serializableis the standard JSON library in KMP. InstallContentNegotiationwithjson(...)in the sharedHttpClient; without it,body<User>()throws at runtime.- The default
Jsonconfiguration rejects unknown keys. Define oneJson { ignoreUnknownKeys = true }incommonMainso a new server field does not break older clients on either platform. - Install
HttpTimeoutin the shared client, not in an engine-specific config block. The Darwin engine supports request and socket timeouts but not a connect timeout. - Gradle: apply
kotlin("multiplatform")and declareandroidTarget(),iosArm64(),iosSimulatorArm64(). Addktor-client-okhttptoandroidMain.dependenciesandktor-client-darwintoiosMain.dependencies. - Kotlin
suspendfunctions export to Swift as completion handlers (callable withasync), butFlowneeds a wrapper such as SKIE or KMP-NativeCoroutines to become anAsyncSequence. - DataStore Preferences supports KMP for shared key-value settings; each platform provides the file path.
Code example
This shows the commonMain contract: a @Serializable model, an ApiClient interface, an expect engine function, a shared KtorApiClient, and a Koin module. The commented lines at the bottom are the actual implementations each platform supplies.
// --- commonMain: shared contract and logic ---
package com.example.data
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.koin.dsl.module
@Serializable
data class User(val id: Int, val name: String)
interface ApiClient {
suspend fun getUser(id: Int): User
}
// Platform boundary: only the engine differs
expect fun createEngine(): HttpClientEngine
val sharedJson = Json { ignoreUnknownKeys = true }
fun createHttpClient(engine: HttpClientEngine): HttpClient =
HttpClient(engine) {
install(ContentNegotiation) { json(sharedJson) }
install(HttpTimeout) { requestTimeoutMillis = 30_000 }
}
class KtorApiClient(private val client: HttpClient) : ApiClient {
override suspend fun getUser(id: Int): User =
client.get("https://api.example.com/users/$id").body()
}
val networkModule = module {
single { createHttpClient(createEngine()) }
single<ApiClient> { KtorApiClient(get()) }
}
// --- androidMain ---
// actual fun createEngine(): HttpClientEngine = OkHttp.create()
// --- iosMain ---
// actual fun createEngine(): HttpClientEngine = Darwin.create()expect fun createEngine()is the onlyexpect/actualhere. The compiler links each target to its ownactual, so there is noif (platform)branch.HttpClient,ContentNegotiation,HttpTimeout, and theJsonconfiguration are written once incommonMain, so both platforms parse and time out the same way.body()(fromio.ktor.client.call) needsContentNegotiation; without it you get a runtime exception, not a compile error.single<ApiClient>binds the interface, so tests can replace it with a fake without touching platform code.
Run the idea in plain Kotlin
interface NetworkEngine {
val name: String
fun fetch(url: String): String
}
class OkHttpEngine : NetworkEngine {
override val name = "OkHttp"
override fun fetch(url: String): String = "200 from " + url
}
class DarwinEngine : NetworkEngine {
override val name = "Darwin"
override fun fetch(url: String): String = "200 from " + url
}
// Shared code: written once, used by both platforms
class UserRepository(private val engine: NetworkEngine) {
fun loadUser(id: Int): String =
"[" + engine.name + "] " + engine.fetch("/api/users/" + id)
}
// Each platform module chooses its engine; the repository never checks the platform
fun platformModule(platform: String): NetworkEngine =
if (platform == "android") OkHttpEngine() else DarwinEngine()
fun main() {
for (platform in listOf("android", "ios")) {
val repo = UserRepository(platformModule(platform))
println(platform + ": " + repo.loadUser(42))
}
println("Same repository, two engines.")
}Expected output:
android: [OkHttp] 200 from /api/users/42
ios: [Darwin] 200 from /api/users/42
Same repository, two engines.
In production
- iOS users saw slow endpoints fail with timeouts while Android users did not.
- The team had set long timeouts inside the OkHttp engine's own configuration in
androidMain. The iOS client used theURLSessiondefaults, so the two platforms timed out at different points. - Android-only testing never exercised the iOS path, so the difference shipped.
- Reproduced it by running the iOS simulator against a local mock server that delayed responses.
- Moved timeout configuration into the shared client in
commonMainwithinstall(HttpTimeout)andrequestTimeoutMillis, and removed the engine-specific timeout settings. - Added the same integration test to CI for both the Android and the iOS simulator targets.
- The backend added an
avatarUrlfield to the user response. - Android had its own
Json { ignoreUnknownKeys = true }passed tojson(...)inandroidMain. The iOS client calledjson()with the default configuration, which rejects unknown keys. - iOS failed with a
SerializationExceptionas soon as the server rollout reached its users; Android kept working.
- Reproduced the failure in a
commonTestunit test that decodes a payload containing the extra field. - Defined one
val sharedJson = Json { ignoreUnknownKeys = true }incommonMainand used it in the single sharedHttpClientfactory. - Removed the platform-specific
HttpClientsetup so configuration cannot diverge again.
Common mistakes
- Putting Context or URLSession in commonMain.
commonMaincannot reference Android or Apple types; the code will not compile. Keep platform types behind anexpectfunction or an interface provided by a platform DI module. - Using Hilt in a KMP module. Hilt is Android-only. Use a multiplatform approach such as Koin or manual constructor injection in shared code.
- Building a separate HttpClient per platform. If Android installs
ContentNegotiationorHttpTimeoutand iOS does not, behaviour differs at runtime. Create the client once incommonMainand pass only the engine in. - Using expect class for the repository.
expect/actualclasses are still Beta in Kotlin 2.x. Prefer an interface incommonMainplus DI so you can swap in a fake for tests. - Adding ktor-client-okhttp to commonMain dependencies. OkHttp is a JVM library and cannot compile for iOS. Put it in
androidMaindependencies.commonMainneedsktor-client-core,ktor-client-content-negotiation, andktor-serialization-kotlinx-json. - Relying on the default Json configuration. It rejects unknown keys, so an additive backend change can break parsing. Define one shared
Jsoninstance with the settings you need.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you structure a shared networking layer in Kotlin Multiplatform?”
“When would you use expect/actual versus an interface with DI in KMP?”
“How do you handle the database layer across Android and iOS?”
“What are the limitations of sharing a Ktor client across platforms?”
Quiz
Which Ktor engine is the usual choice for iOS in a Kotlin Multiplatform project?
Which DI option can you use in commonMain for a KMP project that targets Android and iOS?
What happens if you call body<User>() on a Ktor HttpResponse without installing ContentNegotiation?
What does the default kotlinx.serialization Json configuration do when the server sends a field your @Serializable class does not declare?
0 of 4 answered
Mini task
15-minute exercise: wire a shared Ktor client with Koin
-
Open your KMP project's shared module
build.gradle.kts. InsourceSets, addktor-client-core,ktor-client-content-negotiation,ktor-serialization-kotlinx-json, andkoin-coretocommonMain.dependencies. Apply thekotlin("plugin.serialization")plugin. -
Add
ktor-client-okhttptoandroidMain.dependenciesandktor-client-darwintoiosMain.dependencies. Do not add engine dependencies tocommonMain. -
In
commonMain, createexpect fun createEngine(): HttpClientEngine. InandroidMain, writeactual fun createEngine(): HttpClientEngine = OkHttp.create(). IniosMain, writeactual fun createEngine(): HttpClientEngine = Darwin.create(). -
In
commonMain, create a@Serializable data class User(val id: Int, val name: String)and aninterface ApiClientwithsuspend fun getUser(id: Int): User. -
Implement
KtorApiClientincommonMainusing a sharedHttpClientfactory withContentNegotiationand oneJsoninstance. Write a Koinmodulethat provides theHttpClientand bindsApiClient. -
In
commonMain, addfun initKoin() = startKoin { modules(networkModule) }. Call it from your AndroidApplication.onCreate(), and from Swift at app start (Kotlin exports it with adoprefix, for exampleKoinKt.doInitKoin()if the file isKoin.kt).
Done condition: the project compiles for Android and iosSimulatorArm64. Calling getUser(1) returns a User on both platforms with no platform-specific branching in the repository.