Sharing networking and data layers

Learn to share a Ktor networking client and a SQLDelight or Room database layer across Android and iOS in Kotlin Multiplatform (KMP) with Koin. About 25 minutes.

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 Context in commonMain fails at compile time, but configuration that differs per platform (timeouts, Json settings, 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 (OkHttp on Android, Darwin on iOS).
  • The chef follows the same recipe regardless of stove type (KtorApiClient is platform-agnostic).
  • A kitchen manager (Koin) hands each chef the correct stove at startup.
  • The finished dish (User model) 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.

LayercommonMainandroidMainiosMain
HTTP engineexpect fun createEngine()OkHttp.create()Darwin.create()
DB driverSqlDriver from DIAndroidSqliteDriverNativeSqliteDriver
Models / reposshared——
DIshared Koin moduleplatform moduleplatform 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(): HttpClientEngine is a minimal boundary: OkHttp.create() in androidMain, Darwin.create() in iosMain. expect/actual is 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 module in commonMain wires the HttpClient and repositories; platform modules add Context-dependent pieces.
  • SQLDelight generates Kotlin from .sq files. Each platform supplies an SqlDriver: AndroidSqliteDriver vs NativeSqliteDriver. Room also supports Kotlin Multiplatform since 2.7.
  • kotlinx.serialization with @Serializable is the standard JSON library in KMP. Install ContentNegotiation with json(...) in the shared HttpClient; without it, body<User>() throws at runtime.
  • The default Json configuration rejects unknown keys. Define one Json { ignoreUnknownKeys = true } in commonMain so a new server field does not break older clients on either platform.
  • Install HttpTimeout in 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 declare androidTarget(), iosArm64(), iosSimulatorArm64(). Add ktor-client-okhttp to androidMain.dependencies and ktor-client-darwin to iosMain.dependencies.
  • Kotlin suspend functions export to Swift as completion handlers (callable with async), but Flow needs a wrapper such as SKIE or KMP-NativeCoroutines to become an AsyncSequence.
  • 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 only expect/actual here. The compiler links each target to its own actual, so there is no if (platform) branch.
  • HttpClient, ContentNegotiation, HttpTimeout, and the Json configuration are written once in commonMain, so both platforms parse and time out the same way.
  • body() (from io.ktor.client.call) needs ContentNegotiation; 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

Timeouts configured on one engine only
  • 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 the URLSession defaults, so the two platforms timed out at different points.
  • Android-only testing never exercised the iOS path, so the difference shipped.
The fix
  • Reproduced it by running the iOS simulator against a local mock server that delayed responses.
  • Moved timeout configuration into the shared client in commonMain with install(HttpTimeout) and requestTimeoutMillis, and removed the engine-specific timeout settings.
  • Added the same integration test to CI for both the Android and the iOS simulator targets.
New JSON field broke one platform
  • The backend added an avatarUrl field to the user response.
  • Android had its own Json { ignoreUnknownKeys = true } passed to json(...) in androidMain. The iOS client called json() with the default configuration, which rejects unknown keys.
  • iOS failed with a SerializationException as soon as the server rollout reached its users; Android kept working.
The fix
  • Reproduced the failure in a commonTest unit test that decodes a payload containing the extra field.
  • Defined one val sharedJson = Json { ignoreUnknownKeys = true } in commonMain and used it in the single shared HttpClient factory.
  • Removed the platform-specific HttpClient setup so configuration cannot diverge again.

Common mistakes

  • Putting Context or URLSession in commonMain. commonMain cannot reference Android or Apple types; the code will not compile. Keep platform types behind an expect function 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 ContentNegotiation or HttpTimeout and iOS does not, behaviour differs at runtime. Create the client once in commonMain and pass only the engine in.
  • Using expect class for the repository. expect/actual classes are still Beta in Kotlin 2.x. Prefer an interface in commonMain plus 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 androidMain dependencies. commonMain needs ktor-client-core, ktor-client-content-negotiation, and ktor-serialization-kotlinx-json.
  • Relying on the default Json configuration. It rejects unknown keys, so an additive backend change can break parsing. Define one shared Json instance 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

  1. Open your KMP project's shared module build.gradle.kts. In sourceSets, add ktor-client-core, ktor-client-content-negotiation, ktor-serialization-kotlinx-json, and koin-core to commonMain.dependencies. Apply the kotlin("plugin.serialization") plugin.

  2. Add ktor-client-okhttp to androidMain.dependencies and ktor-client-darwin to iosMain.dependencies. Do not add engine dependencies to commonMain.

  3. In commonMain, create expect fun createEngine(): HttpClientEngine. In androidMain, write actual fun createEngine(): HttpClientEngine = OkHttp.create(). In iosMain, write actual fun createEngine(): HttpClientEngine = Darwin.create().

  4. In commonMain, create a @Serializable data class User(val id: Int, val name: String) and an interface ApiClient with suspend fun getUser(id: Int): User.

  5. Implement KtorApiClient in commonMain using a shared HttpClient factory with ContentNegotiation and one Json instance. Write a Koin module that provides the HttpClient and binds ApiClient.

  6. In commonMain, add fun initKoin() = startKoin { modules(networkModule) }. Call it from your Android Application.onCreate(), and from Swift at app start (Kotlin exports it with a do prefix, for example KoinKt.doInitKoin() if the file is Koin.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.

Next: Compose Multiplatform UI