Skip to content

LanguageIdiomaภาษา

The Unified Codebase: Kotlin Multiplatform Clean Architecture

The Unified Codebase: Kotlin Multiplatform Clean ArchitectureLa codebase unificada: arquitectura limpia en Kotlin Multiplatformโค้ดเบสเดียว: Clean Architecture ของ Kotlin Multiplatform

Kotlin MultiplatformKotlin MultiplatformKotlin Multiplatform

ByPorโดย David Cruz Anaya, Mobile & Applied AI EngineerIngeniero sénior de móvil e IA aplicada (Android, Kotlin Multiplatform, IA de producto)วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

Updated 11 July 2026Actualizado el 11 de julio de 2026อัปเดตเมื่อ 11 กรกฎาคม 20266 min read6 min de lecturaอ่าน 6 นาที
AndroidKotlinKotlin MultiplatformiOSNext.jsClean ArchitectureMobile Development
Share:Compartir:แชร์:

The Unified Codebase Kotlin Multiplatform

Kotlin Multiplatform lets you share your Domain and Data layers (entities, use cases, repositories, and even ViewModels) across Android, iOS, and Next.js while each platform keeps a fully native UI. In this “Headless KMP” approach, you write business logic once in Kotlin and consume it from Jetpack Compose, SwiftUI, and React. This post walks through the full Clean Architecture setup: a feature-based multi-module Gradle project, Koin for dependency injection, Ktor and SQLDelight for data, SKIE for Swift interop, and @JsExport plus a FlowObserver bridge for TypeScript.

Teams keep three codebases, Android, iOS, and Web, or they use Flutter or React Native. Those frameworks draw the UI through their own engines.

KMP leaves the UI on Jetpack Compose, SwiftUI, and the DOM. The Next.js app calls the shared Kotlin from React. It does not render a WebAssembly canvas.

Logic drift

Logic drift is a business rule that diverges across platforms because each platform has its own implementation. A password check or a financial total should match on every screen. The shared Domain layer is where this project keeps that rule in one place.

Android compiles Kotlin to JVM bytecode, and iOS compiles it to an LLVM binary. The Next.js target compiles Kotlin to JavaScript or WebAssembly. The shared code then has to cross from Kotlin coroutines into TypeScript promises.

Clean Architecture

Clean Architecture, as Robert C. Martin describes it, structures an application in concentric circles. The UI and framework layers stay off the core so a platform import, such as UIKit, cannot leak into shared business rules and break the Android and Web builds.

Layers

Source code dependencies point inward.

Layer

Component

Technology Stack

Responsibility

Presentation (Outer)

UI / Views

Jetpack Compose, SwiftUI, React/Next.js

Rendering the state, capturing user input

Presentation (Inner)

ViewModels / Presenters

Shared Kotlin (androidx.lifecycle.ViewModel)

State management, exposing StateFlow to UI

Domain (Core)

Use Cases / Interactors

Pure Kotlin (Common)

Orchestrating business rules

Domain (Core)

Entities

Pure Kotlin (Common)

Enterprise business objects

Data (Inner)

Repositories

Shared Kotlin

Mediating between data sources

Data (Outer)

Data Sources

Ktor, SQLDelight, DataStore

API access, local persistence

ViewModels live in the shared module. Before AndroidX Lifecycle 2.8.0 they were platform-specific. That release made ViewModel and viewModelScope multiplatform, so the state is written once and read from all three platforms.

Domain-Centric Design

The Domain layer is the most stable part of the application. In this architecture, it contains:

Entities are data classes representing the core business model. For Next.js, export them cleanly to JavaScript.

Repository Interfaces are contracts defining data operations, such as UserRepository.

Use Cases are single-responsibility classes that execute specific business actions, such as LoginUseCase.

Defining Repository interfaces in the Domain layer is the inversion of control. The Data layer (outer) depends on the Domain layer (inner) to implement these interfaces, ensuring the business logic remains ignorant of whether the data comes from a SQL database, a REST API, or a mock object during testing.

Project Configuration: The Multi-Module Monorepo

A monolithic shared module often becomes a compilation bottleneck. As the application grows, a single change in a utility class could trigger the recompilation of the entire shared codebase. Split the shared code into feature modules.

Directory Structure

The recommended structure separates the platform-specific application entry points from the shared logic modules:

Root Project
├── build-logic/                  # Custom Gradle Convention Plugins
├── gradle/libs.versions.toml     # Version Catalog
├── app-android/                  # Native Android Application
├── app-ios/                      # Native iOS Xcode Workspace
├── app-web/                      # Next.js TypeScript Project
├── core/                         # Shared Infrastructure
│   ├── common/                   # Logger, Dispatchers, DateTime
│   ├── database/                 # SQLDelight schema and drivers
│   ├── network/                  # Ktor Client configuration
│   └── preferences/              # DataStore implementation
└── features/                     # Shared Business Features
    ├── auth/
    │   ├── domain/               # Pure Kotlin logic
    │   ├── data/                 # Repositories & API
    │   └── ui/                   # Shared ViewModels
    └── feed/
        └── ...

Gradle Version Catalog

Keep one version catalog for the Kotlin toolchain. Inconsistent versions of kotlinx-coroutines or ktor can lead to runtime crashes in the JavaScript target or binary incompatibilities on iOS.

# gradle/libs.versions.toml

[versions]
kotlin = "2.0.0"
agp = "8.4.0"
koin = "3.5.6"
ktor = "2.3.11"
coroutines = "1.8.1"
sqldelight = "2.0.2"
serialization = "1.6.3"
androidxLifecycle = "2.8.0"
skie = "0.8.2" # Critical for Swift interop

[libraries]
# Core Kotlin
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" }
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }

# Networking
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-android = { module = "io.ktor:ktor-client-android", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
ktor-serialization = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }

# Persistence
sqldelight-android = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
sqldelight-native = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
sqldelight-web = { module = "app.cash.sqldelight:web-worker-driver", version.ref = "sqldelight" }

# Architecture
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
androidx-lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel", version.ref = "androidxLifecycle" }

[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
skie = { id = "co.touchlab.skie", version.ref = "skie" }

Module Build Configuration

The build script for a shared feature module must explicitly target Android, iOS, and JavaScript. For Next.js integration, the js(IR) target is configured to generate TypeScript definitions. Those definitions keep the TypeScript codebase typed.

// features/auth/build.gradle.kts

plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidLibrary)
    alias(libs.plugins.serialization)
    alias(libs.plugins.skie) // Enhance Swift Interop
}

kotlin {
    // 1. Android Target
    androidTarget {
        compilations.all {
            kotlinOptions { jvmTarget = "17" }
        }
    }

    // 2. iOS Targets
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "AuthFeature"
            isStatic = true
        }
    }

    // 3. JavaScript Target for Next.js
    js(IR) {
        moduleName = "auth-shared"
        browser {
            webpackTask {
                mainOutputFileName = "auth-shared.js"
            }
        }
        binaries.executable()
        generateTypeScriptDefinitions()
    }

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(libs.coroutines.core)
                implementation(libs.ktor.client.core)
                implementation(libs.ktor.serialization)
                implementation(libs.koin.core)
                api(libs.androidx.lifecycle.viewmodel)
            }
        }
        
        val androidMain by getting {
            dependencies {
                implementation(libs.ktor.client.android)
            }
        }
        
        val iosMain by creating {
            dependsOn(commonMain)
            dependencies {
                implementation(libs.ktor.client.darwin)
            }
        }
        
        val jsMain by getting {
            dependencies {
                implementation(libs.ktor.client.js)
            }
        }
    }
}

Domain Layer Implementation

The Domain layer holds the business logic. It stays free of platform-specific dependencies. Use strict DTOs and mappers at the Domain edge so platform-specific details, such as JS numbers, do not leak into the core logic.

Defining Entities

Entities should be simple data classes with serialization support for cross-platform compatibility:

// features/auth/domain/model/User.kt

package com.example.auth.domain.model

import kotlinx.serialization.Serializable
import kotlin.js.JsExport

@JsExport
@Serializable
data class User(
    val id: String,
    val email: String,
    val displayName: String,
    val avatarUrl: String?
)

@JsExport
@Serializable
data class AuthCredentials(
    val email: String,
    val password: String
)

The @JsExport annotation makes these types accessible from TypeScript in the Next.js application.

Repository Interfaces

Define contracts that the Data layer must implement:

// features/auth/domain/repository/AuthRepository.kt

package com.example.auth.domain.repository

import com.example.auth.domain.model.User
import com.example.auth.domain.model.AuthCredentials

interface AuthRepository {
    suspend fun login(credentials: AuthCredentials): Result<User>
    suspend fun logout()
    suspend fun getCurrentUser(): User?
    suspend fun refreshToken(): Result<Unit>
}

Use Cases

Use Cases encapsulate single business operations:

// features/auth/domain/usecase/LoginUseCase.kt

package com.example.auth.domain.usecase

import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import com.example.auth.domain.repository.AuthRepository

class LoginUseCase(
    private val authRepository: AuthRepository
) {
    suspend operator fun invoke(
        email: String, 
        password: String
    ): Result<User> {
        // Validate input
        if (email.isBlank()) {
            return Result.failure(IllegalArgumentException("Email cannot be empty"))
        }
        if (password.length < 8) {
            return Result.failure(IllegalArgumentException("Password must be at least 8 characters"))
        }
        
        val credentials = AuthCredentials(email, password)
        return authRepository.login(credentials)
    }
}

Presentation Layer: Shared ViewModels

With AndroidX Lifecycle 2.8.0, ViewModels can now live in shared code and expose state via StateFlow:

// features/auth/ui/AuthViewModel.kt

package com.example.auth.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.auth.domain.model.User
import com.example.auth.domain.usecase.LoginUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlin.js.JsExport

@JsExport
sealed class AuthUiState {
    object Idle : AuthUiState()
    object Loading : AuthUiState()
    data class Success(val user: User) : AuthUiState()
    data class Error(val message: String) : AuthUiState()
}

@JsExport
class AuthViewModel(
    private val loginUseCase: LoginUseCase
) : ViewModel() {

    private val _uiState = MutableStateFlow<AuthUiState>(AuthUiState.Idle)
    val uiState: StateFlow<AuthUiState> = _uiState.asStateFlow()

    fun onLogin(email: String, password: String) {
        viewModelScope.launch {
            _uiState.value = AuthUiState.Loading
            
            loginUseCase(email, password)
                .onSuccess { user ->
                    _uiState.value = AuthUiState.Success(user)
                }
                .onFailure { error ->
                    _uiState.value = AuthUiState.Error(
                        error.message ?: "Unknown error occurred"
                    )
                }
        }
    }

    fun resetState() {
        _uiState.value = AuthUiState.Idle
    }
}

Data Layer Implementation

The Data layer implements the repository interfaces and handles platform-specific data operations.

API Service with Ktor

// features/auth/data/api/AuthApiService.kt

package com.example.auth.data.api

import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*

class AuthApiService(
    private val httpClient: HttpClient
) {
    suspend fun login(credentials: AuthCredentials): User {
        return httpClient.post("https://api.example.com/auth/login") {
            contentType(ContentType.Application.Json)
            setBody(credentials)
        }.body()
    }

    suspend fun getCurrentUser(): User? {
        return try {
            httpClient.get("https://api.example.com/auth/me").body()
        } catch (e: Exception) {
            null
        }
    }
}

Repository Implementation

// features/auth/data/repository/AuthRepositoryImpl.kt

package com.example.auth.data.repository

import com.example.auth.data.api.AuthApiService
import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import com.example.auth.domain.repository.AuthRepository

class AuthRepositoryImpl(
    private val apiService: AuthApiService
) : AuthRepository {

    override suspend fun login(credentials: AuthCredentials): Result<User> {
        return try {
            val user = apiService.login(credentials)
            Result.success(user)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun logout() {
        // Clear tokens and cached data
    }

    override suspend fun getCurrentUser(): User? {
        return apiService.getCurrentUser()
    }

    override suspend fun refreshToken(): Result<Unit> {
        // Implement token refresh logic
        return Result.success(Unit)
    }
}

Dependency Injection with Koin

Koin provides a lightweight, multiplatform-compatible DI solution:

// core/common/di/AppModule.kt

package com.example.di

import com.example.auth.data.api.AuthApiService
import com.example.auth.data.repository.AuthRepositoryImpl
import com.example.auth.domain.repository.AuthRepository
import com.example.auth.domain.usecase.LoginUseCase
import com.example.auth.presentation.AuthViewModel
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module

val networkModule = module {
    single {
        HttpClient {
            install(ContentNegotiation) {
                json()
            }
        }
    }
}

val authModule = module {
    single { AuthApiService(get()) }
    single<AuthRepository> { AuthRepositoryImpl(get()) }
    factory { LoginUseCase(get()) }
    factory { AuthViewModel(get()) }
}

val appModules = listOf(networkModule, authModule)

For JavaScript consumption, create a helper object:

// core/common/di/KoinHelper.kt

package com.example.di

import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import kotlin.js.JsExport
import com.example.auth.presentation.AuthViewModel

@JsExport
object KoinHelper : KoinComponent {
    
    fun initKoin() {
        startKoin {
            modules(appModules)
        }
    }
    
    fun getAuthViewModel(): AuthViewModel {
        val viewModel: AuthViewModel by inject()
        return viewModel
    }
}

Platform Integration: Android with Jetpack Compose

Android is the primary target KMP was built around:

// app-android/src/main/java/com/example/android/ui/LoginScreen.kt

package com.example.android.ui

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.auth.presentation.AuthUiState
import com.example.auth.presentation.AuthViewModel
import org.koin.androidx.compose.koinViewModel

@Composable
fun LoginScreen(
    viewModel: AuthViewModel = koinViewModel(),
    onLoginSuccess: () -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    
    LaunchedEffect(uiState) {
        if (uiState is AuthUiState.Success) {
            onLoginSuccess()
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = { Text("Email") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text("Password") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Button(
            onClick = { viewModel.onLogin(email, password) },
            enabled = uiState !is AuthUiState.Loading,
            modifier = Modifier.fillMaxWidth()
        ) {
            if (uiState is AuthUiState.Loading) {
                CircularProgressIndicator(modifier = Modifier.size(24.dp))
            } else {
                Text("Login")
            }
        }
        
        if (uiState is AuthUiState.Error) {
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = (uiState as AuthUiState.Error).message,
                color = MaterialTheme.colorScheme.error
            )
        }
    }
}

Platform Integration: iOS with SwiftUI

For iOS, the SKIE plugin transforms Kotlin’s StateFlow into native Swift async sequences:

// app-ios/Sources/Features/Auth/LoginView.swift

import SwiftUI
import AuthFeature // The KMP framework

struct LoginView: View {
    @StateObject private var viewModel = AuthViewModelWrapper()
    @State private var email = ""
    @State private var password = ""
    
    var body: some View {
        VStack(spacing: 16) {
            TextField("Email", text: $email)
                .textFieldStyle(.roundedBorder)
                .autocapitalization(.none)
            
            SecureField("Password", text: $password)
                .textFieldStyle(.roundedBorder)
            
            Button(action: {
                viewModel.login(email: email, password: password)
            }) {
                if viewModel.isLoading {
                    ProgressView()
                } else {
                    Text("Login")
                        .frame(maxWidth: .infinity)
                }
            }
            .buttonStyle(.borderedProminent)
            .disabled(viewModel.isLoading)
            
            if let error = viewModel.errorMessage {
                Text(error)
                    .foregroundColor(.red)
                    .font(.caption)
            }
        }
        .padding()
    }
}

@MainActor
class AuthViewModelWrapper: ObservableObject {
    private let viewModel: AuthViewModel
    
    @Published var isLoading = false
    @Published var user: User? = nil
    @Published var errorMessage: String? = nil
    
    init() {
        self.viewModel = KoinHelper.shared.getAuthViewModel()
        observeState()
    }
    
    private func observeState() {
        Task {
            // SKIE converts StateFlow to AsyncSequence
            for await state in viewModel.uiState {
                switch state {
                case is AuthUiState.Idle:
                    isLoading = false
                    errorMessage = nil
                case is AuthUiState.Loading:
                    isLoading = true
                    errorMessage = nil
                case let success as AuthUiState.Success:
                    isLoading = false
                    user = success.user
                case let error as AuthUiState.Error:
                    isLoading = false
                    errorMessage = error.message
                default:
                    break
                }
            }
        }
    }
    
    func login(email: String, password: String) {
        viewModel.onLogin(email: email, password: password)
    }
}

Platform Integration: Next.js with TypeScript

The web integration bridges Kotlin’s reactive streams to React state. Script the copy of the generated JS artifacts into the Next.js project on each build.

Flow Observer Utility

Create a utility in Kotlin to help observe StateFlow from JavaScript:

// core/common/util/FlowObserver.kt

package com.example.util

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.StateFlow
import kotlin.js.JsExport

@JsExport
class FlowObserver<T : Any>(
    private val flow: StateFlow<T>
) {
    private var scope: CoroutineScope? = null
    
    fun start(callback: (T) -> Unit) {
        scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
        scope?.launch {
            flow.collect { value ->
                callback(value)
            }
        }
    }
    
    fun stop() {
        scope?.cancel()
        scope = null
    }
}

React Custom Hook

// app-web/src/hooks/useAuthViewModel.ts

'use client';

import { useState, useEffect, useRef } from 'react';
import { com } from 'auth-shared';

// Alias types for clarity
type AuthViewModel = com.example.auth.presentation.AuthViewModel;
type AuthUiState = com.example.auth.presentation.AuthUiState;
const KoinHelper = com.example.di.KoinHelper;

export const useAuthViewModel = () => {
    // Initialize ViewModel once
    const viewModelRef = useRef<AuthViewModel | null>(null);
    if (!viewModelRef.current) {
        viewModelRef.current = KoinHelper.getAuthViewModel();
    }
    const viewModel = viewModelRef.current;

    const [state, setState] = useState<AuthUiState>(viewModel.uiState.value);

    useEffect(() => {
        // Create the observer
        const flowObserver = new com.example.util.FlowObserver(viewModel.uiState);

        flowObserver.start((newState: AuthUiState) => {
            setState(newState);
        });

        // Cleanup on unmount
        return () => {
            flowObserver.stop();
        };
    }, [viewModel]);

    return {
        state,
        login: (email: string, password: string) => viewModel.onLogin(email, password),
        resetState: () => viewModel.resetState()
    };
};

Next.js Page Component

The Kotlin/JS output runs in the JavaScript runtime. If the KMP logic attempts to access browser-specific APIs during the server-side render pass, the application will crash.

// app-web/src/app/login/page.tsx

'use client'; // Mandatory for KMP integration

import { useAuthViewModel } from '@/hooks/useAuthViewModel';
import { useState } from 'react';
import { com } from 'auth-shared';

export default function LoginPage() {
    const { state, login } = useAuthViewModel();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    // Type guards for Kotlin Sealed Classes in JS
    const isLoading = state instanceof com.example.auth.presentation.AuthUiState.Loading;
    const isSuccess = (s: any): s is { user: { displayName: string } } => {
        return s instanceof com.example.auth.presentation.AuthUiState.Success;
    };
    const isError = (s: any): s is { message: string } => {
        return s instanceof com.example.auth.presentation.AuthUiState.Error;
    };

    if (isSuccess(state)) {
        return (
            <main className="flex min-h-screen flex-col items-center justify-center p-24">
                <h1 className="text-4xl font-bold">
                    Welcome, {state.user.displayName}!
                </h1>
            </main>
        );
    }

    return (
        <main className="flex min-h-screen flex-col items-center justify-center p-24">
            <form 
                className="flex flex-col gap-4 w-full max-w-md"
                onSubmit={(e) => {
                    e.preventDefault();
                    login(email, password);
                }}
            >
                <input
                    type="email"
                    placeholder="Email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="px-4 py-2 border rounded"
                />
                <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="px-4 py-2 border rounded"
                />
                <button
                    type="submit"
                    disabled={isLoading}
                    className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
                >
                    {isLoading ? 'Loading...' : 'Login'}
                </button>
                
                {isError(state) && (
                    <p className="text-red-500 text-sm">{state.message}</p>
                )}
            </form>
        </main>
    );
}

How Do You Handle SSR Safety with KMP and Next.js?

When integrating KMP with Next.js, you must consider server-side rendering compatibility:

‘use client’ Directive: All components consuming the KMP hooks must be marked with 'use client' to ensure they run primarily in the browser context.

Lazy Loading: In jsMain, ensure that accessing browser APIs is done lazily or guarded by checks for typeof window !== 'undefined'.

Dynamic Imports: For heavy KMP modules, use next/dynamic with ssr: false to disable server-rendering for those specific component trees.

Trade-offs

Feature

React Native / Flutter

KMP (Headless)

Analysis

UI Rendering

Custom Engine / Native Bridge

Platform UI

The UI stays on Compose, SwiftUI, and React

Code Sharing

UI + logic

Logic only

The shared slice is domain, data, and ViewModels

Web Support

Canvas (Flutter) or DOM (RN Web)

Native DOM (React)

KMP allows standard Next.js features

Performance

Bridge Overhead

JVM on Android, native binary on iOS

Android compiles to JVM bytecode. iOS compiles to a native binary.

Complexity of Build Pipeline: Maintaining a Gradle build that correctly outputs Android AARs, iOS Frameworks, and NPM packages is complex. It requires platform engineering knowledge. Debugging Gradle task dependencies across three ecosystems is non-trivial.

The Mental Context Switching Cost: Developers must understand Kotlin for logic, Swift for iOS UI, and TypeScript for Web UI. This is a higher cognitive load than a pure TypeScript stack. The UI stays on SwiftUI, Compose, and React.

Kotlin/JS Bundle Size: Even with Dead Code Elimination, including the Kotlin Standard Library and Coroutines in the JS bundle adds weight. This is acceptable for complex web apps but may be excessive for simple landing pages.

Interop Friction: SKIE improves the iOS interop, and @JsExport covers the web export. Edge cases remain. Kotlin generics, Long types, and sealed classes require specific handling to feel idiomatic in Swift and TypeScript.

Happy coding!

David Cruz
davthecoder.com

Arquitectura limpia y unificada en Kotlin Multiplatform

Kotlin Multiplatform te deja compartir las capas de dominio y de datos (entidades, casos de uso, repositorios e incluso ViewModels) entre Android, iOS y Next.js, mientras cada plataforma conserva una UI totalmente nativa. En este enfoque de «KMP headless», escribes la lógica de negocio una vez en Kotlin y la consumes desde Jetpack Compose, SwiftUI y React. Este artículo recorre el montaje completo de Clean Architecture: un proyecto Gradle multimódulo por funcionalidad, Koin para la inyección de dependencias, Ktor y SQLDelight para los datos, SKIE para la interoperabilidad con Swift, y @JsExport más un puente FlowObserver para TypeScript.

Los equipos mantienen tres codebases, Android, iOS y web, o usan Flutter o React Native. Esos frameworks dibujan la UI con sus propios motores.

KMP deja la UI en Jetpack Compose, SwiftUI y el DOM. La app de Next.js llama al Kotlin compartido desde React. No renderiza un canvas de WebAssembly.

Deriva de la lógica

La deriva de la lógica es una regla de negocio que diverge entre plataformas porque cada plataforma tiene su propia implementación. Una comprobación de contraseña o un total financiero debería coincidir en cada pantalla. La capa de dominio compartida es donde este proyecto deja esa regla en un solo sitio.

Android compila Kotlin a bytecode de la JVM, e iOS lo compila a un binario LLVM. El destino de Next.js compila Kotlin a JavaScript o a WebAssembly. El código compartido tiene que cruzar entonces de las corrutinas de Kotlin a las promesas de TypeScript.

Clean Architecture

Clean Architecture, como la describe Robert C. Martin, estructura una aplicación en círculos concéntricos. Las capas de UI y de framework se quedan fuera del núcleo para que un import de plataforma, como UIKit, no se cuele en las reglas de negocio compartidas y rompa las compilaciones de Android y de la web.

Capas

Las dependencias del código fuente apuntan hacia dentro.

Capa

Componente

Pila tecnológica

Responsabilidad

Presentación (exterior)

UI / vistas

Jetpack Compose, SwiftUI, React/Next.js

Renderizar el estado y capturar la entrada del usuario

Presentación (interior)

ViewModels / presenters

Kotlin compartido (androidx.lifecycle.ViewModel)

Gestión del estado y exposición de StateFlow a la UI

Dominio (núcleo)

Casos de uso / interactors

Kotlin puro (common)

Orquestar las reglas de negocio

Dominio (núcleo)

Entidades

Kotlin puro (common)

Objetos de negocio de la empresa

Datos (interior)

Repositorios

Kotlin compartido

Mediar entre las fuentes de datos

Datos (exterior)

Fuentes de datos

Ktor, SQLDelight, DataStore

Acceso a la API y persistencia local

Los ViewModels viven en el módulo compartido. Antes de AndroidX Lifecycle 2.8.0 eran específicos de la plataforma. Esa release hizo multiplataforma ViewModel y viewModelScope, así que el estado se escribe una vez y se lee desde las tres plataformas.

Diseño centrado en el dominio

La capa de dominio es la parte más estable de la aplicación. En esta arquitectura contiene:

Las entidades son data classes que representan el modelo de negocio central. Para Next.js, expórtalas limpias a JavaScript.

Las interfaces de repositorio son contratos que definen las operaciones de datos, como UserRepository.

Los casos de uso son clases de responsabilidad única que ejecutan acciones de negocio concretas, como LoginUseCase.

Definir las interfaces de repositorio en la capa de dominio es la inversión de control. La capa de datos (exterior) depende de la capa de dominio (interior) para implementar esas interfaces, y así la lógica de negocio sigue sin saber si los datos vienen de una base de datos SQL, de una API REST o de un objeto mock durante las pruebas.

Configuración del proyecto: el monorepo multimódulo

Un módulo compartido monolítico acaba siendo a menudo un cuello de botella de compilación. A medida que crece la aplicación, un solo cambio en una clase de utilidad puede disparar la recompilación de toda la codebase compartida. Parte el código compartido en módulos por funcionalidad.

Estructura de directorios

La estructura recomendada separa los puntos de entrada de aplicación específicos de cada plataforma de los módulos de lógica compartida:

Root Project
├── build-logic/                  # Custom Gradle Convention Plugins
├── gradle/libs.versions.toml     # Version Catalog
├── app-android/                  # Native Android Application
├── app-ios/                      # Native iOS Xcode Workspace
├── app-web/                      # Next.js TypeScript Project
├── core/                         # Shared Infrastructure
│   ├── common/                   # Logger, Dispatchers, DateTime
│   ├── database/                 # SQLDelight schema and drivers
│   ├── network/                  # Ktor Client configuration
│   └── preferences/              # DataStore implementation
└── features/                     # Shared Business Features
    ├── auth/
    │   ├── domain/               # Pure Kotlin logic
    │   ├── data/                 # Repositories & API
    │   └── ui/                   # Shared ViewModels
    └── feed/
        └── ...

Catálogo de versiones de Gradle

Mantén un solo catálogo de versiones para la cadena de herramientas de Kotlin. Versiones incoherentes de kotlinx-coroutines o de ktor pueden llevar a crashes en tiempo de ejecución en el destino JavaScript, o a incompatibilidades binarias en iOS.

# gradle/libs.versions.toml

[versions]
kotlin = "2.0.0"
agp = "8.4.0"
koin = "3.5.6"
ktor = "2.3.11"
coroutines = "1.8.1"
sqldelight = "2.0.2"
serialization = "1.6.3"
androidxLifecycle = "2.8.0"
skie = "0.8.2" # Critical for Swift interop

[libraries]
# Core Kotlin
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" }
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }

# Networking
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-android = { module = "io.ktor:ktor-client-android", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
ktor-serialization = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }

# Persistence
sqldelight-android = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
sqldelight-native = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
sqldelight-web = { module = "app.cash.sqldelight:web-worker-driver", version.ref = "sqldelight" }

# Architecture
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
androidx-lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel", version.ref = "androidxLifecycle" }

[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
skie = { id = "co.touchlab.skie", version.ref = "skie" }

Configuración de build del módulo

El script de build de un módulo de funcionalidad compartida tiene que apuntar de forma explícita a Android, iOS y JavaScript. Para la integración con Next.js, el target js(IR) se configura para generar definiciones de TypeScript. Esas definiciones mantienen tipada la codebase de TypeScript.

// features/auth/build.gradle.kts

plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidLibrary)
    alias(libs.plugins.serialization)
    alias(libs.plugins.skie) // Enhance Swift Interop
}

kotlin {
    // 1. Android Target
    androidTarget {
        compilations.all {
            kotlinOptions { jvmTarget = "17" }
        }
    }

    // 2. iOS Targets
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "AuthFeature"
            isStatic = true
        }
    }

    // 3. JavaScript Target for Next.js
    js(IR) {
        moduleName = "auth-shared"
        browser {
            webpackTask {
                mainOutputFileName = "auth-shared.js"
            }
        }
        binaries.executable()
        generateTypeScriptDefinitions()
    }

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(libs.coroutines.core)
                implementation(libs.ktor.client.core)
                implementation(libs.ktor.serialization)
                implementation(libs.koin.core)
                api(libs.androidx.lifecycle.viewmodel)
            }
        }
        
        val androidMain by getting {
            dependencies {
                implementation(libs.ktor.client.android)
            }
        }
        
        val iosMain by creating {
            dependsOn(commonMain)
            dependencies {
                implementation(libs.ktor.client.darwin)
            }
        }
        
        val jsMain by getting {
            dependencies {
                implementation(libs.ktor.client.js)
            }
        }
    }
}

Implementación de la capa de dominio

La capa de dominio contiene la lógica de negocio. Se queda libre de dependencias específicas de la plataforma. Usa DTO estrictos y mappers en el edge del dominio para que los detalles específicos de la plataforma, como los números de JS, no se cuelen en la lógica del núcleo.

Definir las entidades

Las entidades deberían ser data classes sencillas, con soporte de serialización para la compatibilidad entre plataformas:

// features/auth/domain/model/User.kt

package com.example.auth.domain.model

import kotlinx.serialization.Serializable
import kotlin.js.JsExport

@JsExport
@Serializable
data class User(
    val id: String,
    val email: String,
    val displayName: String,
    val avatarUrl: String?
)

@JsExport
@Serializable
data class AuthCredentials(
    val email: String,
    val password: String
)

La anotación @JsExport hace que estos tipos sean accesibles desde TypeScript en la aplicación de Next.js.

Interfaces de repositorio

Define los contratos que tiene que implementar la capa de datos:

// features/auth/domain/repository/AuthRepository.kt

package com.example.auth.domain.repository

import com.example.auth.domain.model.User
import com.example.auth.domain.model.AuthCredentials

interface AuthRepository {
    suspend fun login(credentials: AuthCredentials): Result<User>
    suspend fun logout()
    suspend fun getCurrentUser(): User?
    suspend fun refreshToken(): Result<Unit>
}

Casos de uso

Los casos de uso encapsulan operaciones de negocio únicas:

// features/auth/domain/usecase/LoginUseCase.kt

package com.example.auth.domain.usecase

import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import com.example.auth.domain.repository.AuthRepository

class LoginUseCase(
    private val authRepository: AuthRepository
) {
    suspend operator fun invoke(
        email: String, 
        password: String
    ): Result<User> {
        // Validate input
        if (email.isBlank()) {
            return Result.failure(IllegalArgumentException("Email cannot be empty"))
        }
        if (password.length < 8) {
            return Result.failure(IllegalArgumentException("Password must be at least 8 characters"))
        }
        
        val credentials = AuthCredentials(email, password)
        return authRepository.login(credentials)
    }
}

Capa de presentación: ViewModels compartidos

Con AndroidX Lifecycle 2.8.0, los ViewModels pueden vivir ya en el código compartido y exponer el estado mediante StateFlow:

// features/auth/ui/AuthViewModel.kt

package com.example.auth.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.auth.domain.model.User
import com.example.auth.domain.usecase.LoginUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlin.js.JsExport

@JsExport
sealed class AuthUiState {
    object Idle : AuthUiState()
    object Loading : AuthUiState()
    data class Success(val user: User) : AuthUiState()
    data class Error(val message: String) : AuthUiState()
}

@JsExport
class AuthViewModel(
    private val loginUseCase: LoginUseCase
) : ViewModel() {

    private val _uiState = MutableStateFlow<AuthUiState>(AuthUiState.Idle)
    val uiState: StateFlow<AuthUiState> = _uiState.asStateFlow()

    fun onLogin(email: String, password: String) {
        viewModelScope.launch {
            _uiState.value = AuthUiState.Loading
            
            loginUseCase(email, password)
                .onSuccess { user ->
                    _uiState.value = AuthUiState.Success(user)
                }
                .onFailure { error ->
                    _uiState.value = AuthUiState.Error(
                        error.message ?: "Unknown error occurred"
                    )
                }
        }
    }

    fun resetState() {
        _uiState.value = AuthUiState.Idle
    }
}

Implementación de la capa de datos

La capa de datos implementa las interfaces de repositorio y se ocupa de las operaciones de datos específicas de la plataforma.

Servicio de API con Ktor

// features/auth/data/api/AuthApiService.kt

package com.example.auth.data.api

import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*

class AuthApiService(
    private val httpClient: HttpClient
) {
    suspend fun login(credentials: AuthCredentials): User {
        return httpClient.post("https://api.example.com/auth/login") {
            contentType(ContentType.Application.Json)
            setBody(credentials)
        }.body()
    }

    suspend fun getCurrentUser(): User? {
        return try {
            httpClient.get("https://api.example.com/auth/me").body()
        } catch (e: Exception) {
            null
        }
    }
}

Implementación del repositorio

// features/auth/data/repository/AuthRepositoryImpl.kt

package com.example.auth.data.repository

import com.example.auth.data.api.AuthApiService
import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import com.example.auth.domain.repository.AuthRepository

class AuthRepositoryImpl(
    private val apiService: AuthApiService
) : AuthRepository {

    override suspend fun login(credentials: AuthCredentials): Result<User> {
        return try {
            val user = apiService.login(credentials)
            Result.success(user)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun logout() {
        // Clear tokens and cached data
    }

    override suspend fun getCurrentUser(): User? {
        return apiService.getCurrentUser()
    }

    override suspend fun refreshToken(): Result<Unit> {
        // Implement token refresh logic
        return Result.success(Unit)
    }
}

Inyección de dependencias con Koin

Koin ofrece una solución de DI ligera y compatible con multiplataforma:

// core/common/di/AppModule.kt

package com.example.di

import com.example.auth.data.api.AuthApiService
import com.example.auth.data.repository.AuthRepositoryImpl
import com.example.auth.domain.repository.AuthRepository
import com.example.auth.domain.usecase.LoginUseCase
import com.example.auth.presentation.AuthViewModel
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module

val networkModule = module {
    single {
        HttpClient {
            install(ContentNegotiation) {
                json()
            }
        }
    }
}

val authModule = module {
    single { AuthApiService(get()) }
    single<AuthRepository> { AuthRepositoryImpl(get()) }
    factory { LoginUseCase(get()) }
    factory { AuthViewModel(get()) }
}

val appModules = listOf(networkModule, authModule)

Para el consumo desde JavaScript, crea un objeto de ayuda:

// core/common/di/KoinHelper.kt

package com.example.di

import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import kotlin.js.JsExport
import com.example.auth.presentation.AuthViewModel

@JsExport
object KoinHelper : KoinComponent {
    
    fun initKoin() {
        startKoin {
            modules(appModules)
        }
    }
    
    fun getAuthViewModel(): AuthViewModel {
        val viewModel: AuthViewModel by inject()
        return viewModel
    }
}

Integración de plataforma: Android con Jetpack Compose

Android es el destino principal para el que se construyó KMP:

// app-android/src/main/java/com/example/android/ui/LoginScreen.kt

package com.example.android.ui

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.auth.presentation.AuthUiState
import com.example.auth.presentation.AuthViewModel
import org.koin.androidx.compose.koinViewModel

@Composable
fun LoginScreen(
    viewModel: AuthViewModel = koinViewModel(),
    onLoginSuccess: () -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    
    LaunchedEffect(uiState) {
        if (uiState is AuthUiState.Success) {
            onLoginSuccess()
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = { Text("Email") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text("Password") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Button(
            onClick = { viewModel.onLogin(email, password) },
            enabled = uiState !is AuthUiState.Loading,
            modifier = Modifier.fillMaxWidth()
        ) {
            if (uiState is AuthUiState.Loading) {
                CircularProgressIndicator(modifier = Modifier.size(24.dp))
            } else {
                Text("Login")
            }
        }
        
        if (uiState is AuthUiState.Error) {
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = (uiState as AuthUiState.Error).message,
                color = MaterialTheme.colorScheme.error
            )
        }
    }
}

Integración de plataforma: iOS con SwiftUI

En iOS, el plugin SKIE transforma el StateFlow de Kotlin en secuencias asíncronas nativas de Swift:

// app-ios/Sources/Features/Auth/LoginView.swift

import SwiftUI
import AuthFeature // The KMP framework

struct LoginView: View {
    @StateObject private var viewModel = AuthViewModelWrapper()
    @State private var email = ""
    @State private var password = ""
    
    var body: some View {
        VStack(spacing: 16) {
            TextField("Email", text: $email)
                .textFieldStyle(.roundedBorder)
                .autocapitalization(.none)
            
            SecureField("Password", text: $password)
                .textFieldStyle(.roundedBorder)
            
            Button(action: {
                viewModel.login(email: email, password: password)
            }) {
                if viewModel.isLoading {
                    ProgressView()
                } else {
                    Text("Login")
                        .frame(maxWidth: .infinity)
                }
            }
            .buttonStyle(.borderedProminent)
            .disabled(viewModel.isLoading)
            
            if let error = viewModel.errorMessage {
                Text(error)
                    .foregroundColor(.red)
                    .font(.caption)
            }
        }
        .padding()
    }
}

@MainActor
class AuthViewModelWrapper: ObservableObject {
    private let viewModel: AuthViewModel
    
    @Published var isLoading = false
    @Published var user: User? = nil
    @Published var errorMessage: String? = nil
    
    init() {
        self.viewModel = KoinHelper.shared.getAuthViewModel()
        observeState()
    }
    
    private func observeState() {
        Task {
            // SKIE converts StateFlow to AsyncSequence
            for await state in viewModel.uiState {
                switch state {
                case is AuthUiState.Idle:
                    isLoading = false
                    errorMessage = nil
                case is AuthUiState.Loading:
                    isLoading = true
                    errorMessage = nil
                case let success as AuthUiState.Success:
                    isLoading = false
                    user = success.user
                case let error as AuthUiState.Error:
                    isLoading = false
                    errorMessage = error.message
                default:
                    break
                }
            }
        }
    }
    
    func login(email: String, password: String) {
        viewModel.onLogin(email: email, password: password)
    }
}

Integración de plataforma: Next.js con TypeScript

La integración web tiende un puente entre los streams reactivos de Kotlin y el estado de React. Programa la copia de los artefactos de JS generados al proyecto de Next.js en cada build.

Utilidad de observación de Flow

Crea una utilidad en Kotlin que ayude a observar un StateFlow desde JavaScript:

// core/common/util/FlowObserver.kt

package com.example.util

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.StateFlow
import kotlin.js.JsExport

@JsExport
class FlowObserver<T : Any>(
    private val flow: StateFlow<T>
) {
    private var scope: CoroutineScope? = null
    
    fun start(callback: (T) -> Unit) {
        scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
        scope?.launch {
            flow.collect { value ->
                callback(value)
            }
        }
    }
    
    fun stop() {
        scope?.cancel()
        scope = null
    }
}

Hook personalizado de React

// app-web/src/hooks/useAuthViewModel.ts

'use client';

import { useState, useEffect, useRef } from 'react';
import { com } from 'auth-shared';

// Alias types for clarity
type AuthViewModel = com.example.auth.presentation.AuthViewModel;
type AuthUiState = com.example.auth.presentation.AuthUiState;
const KoinHelper = com.example.di.KoinHelper;

export const useAuthViewModel = () => {
    // Initialize ViewModel once
    const viewModelRef = useRef<AuthViewModel | null>(null);
    if (!viewModelRef.current) {
        viewModelRef.current = KoinHelper.getAuthViewModel();
    }
    const viewModel = viewModelRef.current;

    const [state, setState] = useState<AuthUiState>(viewModel.uiState.value);

    useEffect(() => {
        // Create the observer
        const flowObserver = new com.example.util.FlowObserver(viewModel.uiState);

        flowObserver.start((newState: AuthUiState) => {
            setState(newState);
        });

        // Cleanup on unmount
        return () => {
            flowObserver.stop();
        };
    }, [viewModel]);

    return {
        state,
        login: (email: string, password: string) => viewModel.onLogin(email, password),
        resetState: () => viewModel.resetState()
    };
};

Componente de página de Next.js

El resultado de Kotlin/JS corre en el runtime de JavaScript. Si la lógica de KMP intenta acceder a API específicas del navegador durante el pase de renderizado en el servidor, la aplicación va a cascar.

// app-web/src/app/login/page.tsx

'use client'; // Mandatory for KMP integration

import { useAuthViewModel } from '@/hooks/useAuthViewModel';
import { useState } from 'react';
import { com } from 'auth-shared';

export default function LoginPage() {
    const { state, login } = useAuthViewModel();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    // Type guards for Kotlin Sealed Classes in JS
    const isLoading = state instanceof com.example.auth.presentation.AuthUiState.Loading;
    const isSuccess = (s: any): s is { user: { displayName: string } } => {
        return s instanceof com.example.auth.presentation.AuthUiState.Success;
    };
    const isError = (s: any): s is { message: string } => {
        return s instanceof com.example.auth.presentation.AuthUiState.Error;
    };

    if (isSuccess(state)) {
        return (
            <main className="flex min-h-screen flex-col items-center justify-center p-24">
                <h1 className="text-4xl font-bold">
                    Welcome, {state.user.displayName}!
                </h1>
            </main>
        );
    }

    return (
        <main className="flex min-h-screen flex-col items-center justify-center p-24">
            <form 
                className="flex flex-col gap-4 w-full max-w-md"
                onSubmit={(e) => {
                    e.preventDefault();
                    login(email, password);
                }}
            >
                <input
                    type="email"
                    placeholder="Email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="px-4 py-2 border rounded"
                />
                <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="px-4 py-2 border rounded"
                />
                <button
                    type="submit"
                    disabled={isLoading}
                    className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
                >
                    {isLoading ? 'Loading...' : 'Login'}
                </button>
                
                {isError(state) && (
                    <p className="text-red-500 text-sm">{state.message}</p>
                )}
            </form>
        </main>
    );
}

¿Cómo gestionas la seguridad del SSR con KMP y Next.js?

Al integrar KMP con Next.js, tienes que tener en cuenta la compatibilidad con el renderizado en el servidor:

Directiva ‘use client’: todos los componentes que consuman los hooks de KMP tienen que marcarse con 'use client' para que se ejecuten sobre todo en el contexto del navegador.

Carga perezosa: en jsMain, asegúrate de que el acceso a las API del navegador se hace de forma perezosa, o protegido por comprobaciones de typeof window !== 'undefined'.

Imports dinámicos: para los módulos de KMP pesados, usa next/dynamic con ssr: false para desactivar el renderizado en el servidor de esos árboles de componentes concretos.

Contraprestaciones

Característica

React Native / Flutter

KMP (headless)

Análisis

Renderizado de la UI

Motor propio / puente nativo

UI de plataforma

La UI se queda en Compose, SwiftUI y React

Código compartido

UI + lógica

Solo lógica

La parte compartida es el dominio, los datos y los ViewModels

Soporte web

Canvas (Flutter) o DOM (RN Web)

DOM nativo (React)

KMP permite las funciones habituales de Next.js

Rendimiento

Coste del puente

JVM en Android, binario nativo en iOS

Android compila a bytecode de la JVM. iOS compila a un binario nativo.

Complejidad del pipeline de build: mantener un build de Gradle que produzca correctamente AAR de Android, frameworks de iOS y paquetes de NPM es complejo. Exige conocimiento de ingeniería de plataforma. Depurar las dependencias de tareas de Gradle a través de tres ecosistemas no es trivial.

El coste de cambiar de contexto mental: hay que entender Kotlin para la lógica, Swift para la UI de iOS y TypeScript para la UI web. Es una carga cognitiva mayor que la de una pila solo de TypeScript. La UI se queda en SwiftUI, Compose y React.

Tamaño del bundle de Kotlin/JS: incluso con eliminación de código muerto, incluir la biblioteca estándar de Kotlin y las corrutinas en el bundle de JS añade peso. Es aceptable para apps web complejas, pero puede ser excesivo para páginas de aterrizaje sencillas.

Fricción de interoperabilidad: SKIE mejora la interoperabilidad con iOS, y @JsExport cubre la exportación web. Siguen los casos límite. Los genéricos de Kotlin, los tipos Long y las sealed classes exigen un tratamiento concreto para sentirse idiomáticos en Swift y en TypeScript.

¡A programar!

David Cruz
davthecoder.com

โค้ดเบสเดียวของ Kotlin Multiplatform

Kotlin Multiplatform ให้คุณแชร์เลเยอร์ Domain และ Data (entity, use case, repository และแม้แต่ ViewModel) ข้าม Android, iOS และ Next.js โดยแต่ละแพลตฟอร์มยังมี UI ที่เป็น native เต็มรูปแบบ ในแนวทาง “Headless KMP” นี้ คุณเขียน business logic ครั้งเดียวใน Kotlin แล้วเรียกใช้จาก Jetpack Compose, SwiftUI และ React โพสต์นี้เดินผ่านการตั้งค่า Clean Architecture ทั้งชุด โปรเจกต์ Gradle หลายโมดูลตามฟีเจอร์, Koin สำหรับ dependency injection, Ktor และ SQLDelight สำหรับข้อมูล, SKIE สำหรับ Swift interop และ @JsExport พร้อมสะพาน FlowObserver สำหรับ TypeScript

ทีมเก็บสามโค้ดเบส คือ Android, iOS และ Web หรือใช้ Flutter หรือ React Native เฟรมเวิร์กเหล่านั้นวาด UI ผ่านเอนจินของตัวเอง

KMP ทิ้ง UI ไว้บน Jetpack Compose, SwiftUI และ DOM แอป Next.js เรียก Kotlin ที่แชร์จาก React มันไม่เรนเดอร์แคนวาส WebAssembly

Logic drift

Logic drift คือกฎธุรกิจที่แยกทางกันข้ามแพลตฟอร์ม เพราะแต่ละแพลตฟอร์มมี implementation ของตัวเอง การตรวจรหัสผ่านหรือยอดการเงินควรตรงกันบนทุกหน้าจอ เลเยอร์ Domain ที่แชร์คือที่ที่โปรเจกต์นี้เก็บกฎนั้นไว้ที่เดียว

Android คอมไพล์ Kotlin เป็น JVM bytecode และ iOS คอมไพล์เป็นไบนารี LLVM เป้าหมาย Next.js คอมไพล์ Kotlin เป็น JavaScript หรือ WebAssembly โค้ดที่แชร์จึงต้องข้ามจาก coroutine ของ Kotlin ไปเป็น promise ของ TypeScript

Clean Architecture

Clean Architecture ตามที่ Robert C. Martin อธิบาย จัดโครงสร้างแอปพลิเคชันเป็นวงกลมซ้อนกัน เลเยอร์ UI และเฟรมเวิร์กอยู่ห่างจากแกน เพื่อไม่ให้ import ของแพลตฟอร์ม เช่น UIKit รั่วเข้ากฎธุรกิจที่แชร์ แล้วทำให้บิลด์ Android และ Web พัง

เลเยอร์

dependency ของซอร์สโค้ดชี้เข้าด้านใน

เลเยอร์

คอมโพเนนต์

สแต็กเทคโนโลยี

ความรับผิดชอบ

Presentation (ด้านนอก)

UI / Views

Jetpack Compose, SwiftUI, React/Next.js

เรนเดอร์ state, รับอินพุตจากผู้ใช้

Presentation (ด้านใน)

ViewModels / Presenters

Shared Kotlin (androidx.lifecycle.ViewModel)

จัดการ state, เปิด StateFlow ให้ UI

Domain (แกน)

Use Cases / Interactors

Pure Kotlin (Common)

จัดเรียงกฎธุรกิจ

Domain (แกน)

Entities

Pure Kotlin (Common)

อ็อบเจกต์ธุรกิจขององค์กร

Data (ด้านใน)

Repositories

Shared Kotlin

เป็นตัวกลางระหว่างแหล่งข้อมูล

Data (ด้านนอก)

Data Sources

Ktor, SQLDelight, DataStore

เข้าถึง API, เก็บข้อมูลในเครื่อง

ViewModel อยู่ในโมดูลที่แชร์ ก่อน AndroidX Lifecycle 2.8.0 พวกมันผูกกับแพลตฟอร์ม รีลีสนั้นทำให้ ViewModel และ viewModelScope เป็น multiplatform ดังนั้น state ถูกเขียนครั้งเดียวและอ่านจากทั้งสามแพลตฟอร์ม

การออกแบบที่ยึด Domain

เลเยอร์ Domain เป็นส่วนที่เสถียรที่สุดของแอปพลิเคชัน ในสถาปัตยกรรมนี้มี

Entities เป็น data class ที่แทนโมเดลธุรกิจหลัก สำหรับ Next.js ให้ export พวกมันไป JavaScript อย่างสะอาด

Repository Interfaces เป็นสัญญาที่กำหนดการทำงานกับข้อมูล เช่น UserRepository

Use Cases เป็นคลาสหน้าที่เดียวที่ทำธุรกิจเฉพาะอย่าง เช่น LoginUseCase

การกำหนด interface ของ Repository ในเลเยอร์ Domain คือ inversion of control เลเยอร์ Data (ด้านนอก) พึ่งเลเยอร์ Domain (ด้านใน) เพื่อ implement interface เหล่านี้ ทำให้ business logic ไม่รู้ว่าข้อมูลมาจากฐานข้อมูล SQL, REST API หรือ mock object ตอนเทส

การตั้งค่าโปรเจกต์: monorepo หลายโมดูล

โมดูลแชร์ก้อนเดียวมักกลายเป็นคอขวดของการคอมไพล์ เมื่อแอปโตขึ้น การเปลี่ยนคลาสยูทิลิตี้คลาสเดียวอาจกระตุ้นการคอมไพล์ใหม่ทั้งโค้ดเบสที่แชร์ แยกโค้ดที่แชร์เป็นโมดูลตามฟีเจอร์

โครงสร้างไดเรกทอรี

โครงสร้างที่แนะนำแยกจุดเข้าแอปที่เฉพาะแพลตฟอร์มออกจากโมดูลลอจิกที่แชร์

Root Project
├── build-logic/                  # Custom Gradle Convention Plugins
├── gradle/libs.versions.toml     # Version Catalog
├── app-android/                  # Native Android Application
├── app-ios/                      # Native iOS Xcode Workspace
├── app-web/                      # Next.js TypeScript Project
├── core/                         # Shared Infrastructure
│   ├── common/                   # Logger, Dispatchers, DateTime
│   ├── database/                 # SQLDelight schema and drivers
│   ├── network/                  # Ktor Client configuration
│   └── preferences/              # DataStore implementation
└── features/                     # Shared Business Features
    ├── auth/
    │   ├── domain/               # Pure Kotlin logic
    │   ├── data/                 # Repositories & API
    │   └── ui/                   # Shared ViewModels
    └── feed/
        └── ...

Gradle Version Catalog

เก็บ version catalog เดียวสำหรับ toolchain ของ Kotlin เวอร์ชันของ kotlinx-coroutines หรือ ktor ที่ไม่ตรงกันอาจทำให้ crash ตอนรันบนเป้าหมาย JavaScript หรือไบนารีไม่เข้ากันบน iOS

# gradle/libs.versions.toml

[versions]
kotlin = "2.0.0"
agp = "8.4.0"
koin = "3.5.6"
ktor = "2.3.11"
coroutines = "1.8.1"
sqldelight = "2.0.2"
serialization = "1.6.3"
androidxLifecycle = "2.8.0"
skie = "0.8.2" # Critical for Swift interop

[libraries]
# Core Kotlin
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" }
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }

# Networking
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-android = { module = "io.ktor:ktor-client-android", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
ktor-serialization = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }

# Persistence
sqldelight-android = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
sqldelight-native = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
sqldelight-web = { module = "app.cash.sqldelight:web-worker-driver", version.ref = "sqldelight" }

# Architecture
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
androidx-lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel", version.ref = "androidxLifecycle" }

[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
skie = { id = "co.touchlab.skie", version.ref = "skie" }

การตั้งค่าบิลด์ของโมดูล

สคริปต์บิลด์ของโมดูลฟีเจอร์ที่แชร์ต้องกำหนดเป้าหมาย Android, iOS และ JavaScript อย่างชัดเจน สำหรับการเชื่อม Next.js เป้าหมาย js(IR) ถูกตั้งให้สร้าง TypeScript definition. definition เหล่านั้นคง type ของโค้ดเบส TypeScript ไว้

// features/auth/build.gradle.kts

plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidLibrary)
    alias(libs.plugins.serialization)
    alias(libs.plugins.skie) // Enhance Swift Interop
}

kotlin {
    // 1. Android Target
    androidTarget {
        compilations.all {
            kotlinOptions { jvmTarget = "17" }
        }
    }

    // 2. iOS Targets
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "AuthFeature"
            isStatic = true
        }
    }

    // 3. JavaScript Target for Next.js
    js(IR) {
        moduleName = "auth-shared"
        browser {
            webpackTask {
                mainOutputFileName = "auth-shared.js"
            }
        }
        binaries.executable()
        generateTypeScriptDefinitions()
    }

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(libs.coroutines.core)
                implementation(libs.ktor.client.core)
                implementation(libs.ktor.serialization)
                implementation(libs.koin.core)
                api(libs.androidx.lifecycle.viewmodel)
            }
        }
        
        val androidMain by getting {
            dependencies {
                implementation(libs.ktor.client.android)
            }
        }
        
        val iosMain by creating {
            dependsOn(commonMain)
            dependencies {
                implementation(libs.ktor.client.darwin)
            }
        }
        
        val jsMain by getting {
            dependencies {
                implementation(libs.ktor.client.js)
            }
        }
    }
}

การทำเลเยอร์ Domain

เลเยอร์ Domain ถือ business logic มันปลอดจาก dependency ที่เฉพาะแพลตฟอร์ม ใช้ DTO และ mapper ที่เข้มงวดที่ขอบ Domain เพื่อไม่ให้รายละเอียดเฉพาะแพลตฟอร์ม เช่น ตัวเลขของ JS รั่วเข้าลอจิกแกน

การกำหนด Entity

Entity ควรเป็น data class เรียบง่ายที่รองรับ serialization เพื่อความเข้ากันข้ามแพลตฟอร์ม

// features/auth/domain/model/User.kt

package com.example.auth.domain.model

import kotlinx.serialization.Serializable
import kotlin.js.JsExport

@JsExport
@Serializable
data class User(
    val id: String,
    val email: String,
    val displayName: String,
    val avatarUrl: String?
)

@JsExport
@Serializable
data class AuthCredentials(
    val email: String,
    val password: String
)

แอโนเทชัน @JsExport ทำให้ type เหล่านี้เข้าถึงได้จาก TypeScript ในแอป Next.js

อินเทอร์เฟซของ Repository

กำหนดสัญญาที่เลเยอร์ Data ต้อง implement

// features/auth/domain/repository/AuthRepository.kt

package com.example.auth.domain.repository

import com.example.auth.domain.model.User
import com.example.auth.domain.model.AuthCredentials

interface AuthRepository {
    suspend fun login(credentials: AuthCredentials): Result<User>
    suspend fun logout()
    suspend fun getCurrentUser(): User?
    suspend fun refreshToken(): Result<Unit>
}

Use Case

Use Case ห่อการทำงานธุรกิจครั้งเดียว

// features/auth/domain/usecase/LoginUseCase.kt

package com.example.auth.domain.usecase

import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import com.example.auth.domain.repository.AuthRepository

class LoginUseCase(
    private val authRepository: AuthRepository
) {
    suspend operator fun invoke(
        email: String, 
        password: String
    ): Result<User> {
        // Validate input
        if (email.isBlank()) {
            return Result.failure(IllegalArgumentException("Email cannot be empty"))
        }
        if (password.length < 8) {
            return Result.failure(IllegalArgumentException("Password must be at least 8 characters"))
        }
        
        val credentials = AuthCredentials(email, password)
        return authRepository.login(credentials)
    }
}

เลเยอร์ Presentation: ViewModel ที่แชร์

ด้วย AndroidX Lifecycle 2.8.0 ViewModel อยู่ในโค้ดที่แชร์ได้ และเปิด state ผ่าน StateFlow

// features/auth/ui/AuthViewModel.kt

package com.example.auth.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.auth.domain.model.User
import com.example.auth.domain.usecase.LoginUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlin.js.JsExport

@JsExport
sealed class AuthUiState {
    object Idle : AuthUiState()
    object Loading : AuthUiState()
    data class Success(val user: User) : AuthUiState()
    data class Error(val message: String) : AuthUiState()
}

@JsExport
class AuthViewModel(
    private val loginUseCase: LoginUseCase
) : ViewModel() {

    private val _uiState = MutableStateFlow<AuthUiState>(AuthUiState.Idle)
    val uiState: StateFlow<AuthUiState> = _uiState.asStateFlow()

    fun onLogin(email: String, password: String) {
        viewModelScope.launch {
            _uiState.value = AuthUiState.Loading
            
            loginUseCase(email, password)
                .onSuccess { user ->
                    _uiState.value = AuthUiState.Success(user)
                }
                .onFailure { error ->
                    _uiState.value = AuthUiState.Error(
                        error.message ?: "Unknown error occurred"
                    )
                }
        }
    }

    fun resetState() {
        _uiState.value = AuthUiState.Idle
    }
}

การทำเลเยอร์ Data

เลเยอร์ Data implement interface ของ repository และจัดการการทำงานกับข้อมูลที่เฉพาะแพลตฟอร์ม

API Service ด้วย Ktor

// features/auth/data/api/AuthApiService.kt

package com.example.auth.data.api

import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*

class AuthApiService(
    private val httpClient: HttpClient
) {
    suspend fun login(credentials: AuthCredentials): User {
        return httpClient.post("https://api.example.com/auth/login") {
            contentType(ContentType.Application.Json)
            setBody(credentials)
        }.body()
    }

    suspend fun getCurrentUser(): User? {
        return try {
            httpClient.get("https://api.example.com/auth/me").body()
        } catch (e: Exception) {
            null
        }
    }
}

การ implement Repository

// features/auth/data/repository/AuthRepositoryImpl.kt

package com.example.auth.data.repository

import com.example.auth.data.api.AuthApiService
import com.example.auth.domain.model.AuthCredentials
import com.example.auth.domain.model.User
import com.example.auth.domain.repository.AuthRepository

class AuthRepositoryImpl(
    private val apiService: AuthApiService
) : AuthRepository {

    override suspend fun login(credentials: AuthCredentials): Result<User> {
        return try {
            val user = apiService.login(credentials)
            Result.success(user)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun logout() {
        // Clear tokens and cached data
    }

    override suspend fun getCurrentUser(): User? {
        return apiService.getCurrentUser()
    }

    override suspend fun refreshToken(): Result<Unit> {
        // Implement token refresh logic
        return Result.success(Unit)
    }
}

Dependency Injection ด้วย Koin

Koin ให้โซลูชัน DI ที่เบาและใช้กับ multiplatform ได้

// core/common/di/AppModule.kt

package com.example.di

import com.example.auth.data.api.AuthApiService
import com.example.auth.data.repository.AuthRepositoryImpl
import com.example.auth.domain.repository.AuthRepository
import com.example.auth.domain.usecase.LoginUseCase
import com.example.auth.presentation.AuthViewModel
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module

val networkModule = module {
    single {
        HttpClient {
            install(ContentNegotiation) {
                json()
            }
        }
    }
}

val authModule = module {
    single { AuthApiService(get()) }
    single<AuthRepository> { AuthRepositoryImpl(get()) }
    factory { LoginUseCase(get()) }
    factory { AuthViewModel(get()) }
}

val appModules = listOf(networkModule, authModule)

สำหรับการใช้จาก JavaScript สร้างอ็อบเจกต์ตัวช่วย

// core/common/di/KoinHelper.kt

package com.example.di

import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import kotlin.js.JsExport
import com.example.auth.presentation.AuthViewModel

@JsExport
object KoinHelper : KoinComponent {
    
    fun initKoin() {
        startKoin {
            modules(appModules)
        }
    }
    
    fun getAuthViewModel(): AuthViewModel {
        val viewModel: AuthViewModel by inject()
        return viewModel
    }
}

การเชื่อมแพลตฟอร์ม: Android ด้วย Jetpack Compose

Android เป็นเป้าหมายหลักที่ KMP ถูกสร้างมาเพื่อ

// app-android/src/main/java/com/example/android/ui/LoginScreen.kt

package com.example.android.ui

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.auth.presentation.AuthUiState
import com.example.auth.presentation.AuthViewModel
import org.koin.androidx.compose.koinViewModel

@Composable
fun LoginScreen(
    viewModel: AuthViewModel = koinViewModel(),
    onLoginSuccess: () -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    
    LaunchedEffect(uiState) {
        if (uiState is AuthUiState.Success) {
            onLoginSuccess()
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = { Text("Email") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text("Password") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Button(
            onClick = { viewModel.onLogin(email, password) },
            enabled = uiState !is AuthUiState.Loading,
            modifier = Modifier.fillMaxWidth()
        ) {
            if (uiState is AuthUiState.Loading) {
                CircularProgressIndicator(modifier = Modifier.size(24.dp))
            } else {
                Text("Login")
            }
        }
        
        if (uiState is AuthUiState.Error) {
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = (uiState as AuthUiState.Error).message,
                color = MaterialTheme.colorScheme.error
            )
        }
    }
}

การเชื่อมแพลตฟอร์ม: iOS ด้วย SwiftUI

สำหรับ iOS ปลั๊กอิน SKIE แปลง StateFlow ของ Kotlin เป็น async sequence แบบ native ของ Swift

// app-ios/Sources/Features/Auth/LoginView.swift

import SwiftUI
import AuthFeature // The KMP framework

struct LoginView: View {
    @StateObject private var viewModel = AuthViewModelWrapper()
    @State private var email = ""
    @State private var password = ""
    
    var body: some View {
        VStack(spacing: 16) {
            TextField("Email", text: $email)
                .textFieldStyle(.roundedBorder)
                .autocapitalization(.none)
            
            SecureField("Password", text: $password)
                .textFieldStyle(.roundedBorder)
            
            Button(action: {
                viewModel.login(email: email, password: password)
            }) {
                if viewModel.isLoading {
                    ProgressView()
                } else {
                    Text("Login")
                        .frame(maxWidth: .infinity)
                }
            }
            .buttonStyle(.borderedProminent)
            .disabled(viewModel.isLoading)
            
            if let error = viewModel.errorMessage {
                Text(error)
                    .foregroundColor(.red)
                    .font(.caption)
            }
        }
        .padding()
    }
}

@MainActor
class AuthViewModelWrapper: ObservableObject {
    private let viewModel: AuthViewModel
    
    @Published var isLoading = false
    @Published var user: User? = nil
    @Published var errorMessage: String? = nil
    
    init() {
        self.viewModel = KoinHelper.shared.getAuthViewModel()
        observeState()
    }
    
    private func observeState() {
        Task {
            // SKIE converts StateFlow to AsyncSequence
            for await state in viewModel.uiState {
                switch state {
                case is AuthUiState.Idle:
                    isLoading = false
                    errorMessage = nil
                case is AuthUiState.Loading:
                    isLoading = true
                    errorMessage = nil
                case let success as AuthUiState.Success:
                    isLoading = false
                    user = success.user
                case let error as AuthUiState.Error:
                    isLoading = false
                    errorMessage = error.message
                default:
                    break
                }
            }
        }
    }
    
    func login(email: String, password: String) {
        viewModel.onLogin(email: email, password: password)
    }
}

การเชื่อมแพลตฟอร์ม: Next.js ด้วย TypeScript

การเชื่อมเว็บเป็นสะพานจาก reactive stream ของ Kotlin ไปยัง state ของ React ให้สคริปต์คัดลอก artifact JS ที่สร้างแล้วเข้าโปรเจกต์ Next.js ในทุกบิลด์

ยูทิลิตี้ Flow Observer

สร้างยูทิลิตี้ใน Kotlin เพื่อช่วยสังเกต StateFlow จาก JavaScript

// core/common/util/FlowObserver.kt

package com.example.util

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.StateFlow
import kotlin.js.JsExport

@JsExport
class FlowObserver<T : Any>(
    private val flow: StateFlow<T>
) {
    private var scope: CoroutineScope? = null
    
    fun start(callback: (T) -> Unit) {
        scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
        scope?.launch {
            flow.collect { value ->
                callback(value)
            }
        }
    }
    
    fun stop() {
        scope?.cancel()
        scope = null
    }
}

Hook ของ React

// app-web/src/hooks/useAuthViewModel.ts

'use client';

import { useState, useEffect, useRef } from 'react';
import { com } from 'auth-shared';

// Alias types for clarity
type AuthViewModel = com.example.auth.presentation.AuthViewModel;
type AuthUiState = com.example.auth.presentation.AuthUiState;
const KoinHelper = com.example.di.KoinHelper;

export const useAuthViewModel = () => {
    // Initialize ViewModel once
    const viewModelRef = useRef<AuthViewModel | null>(null);
    if (!viewModelRef.current) {
        viewModelRef.current = KoinHelper.getAuthViewModel();
    }
    const viewModel = viewModelRef.current;

    const [state, setState] = useState<AuthUiState>(viewModel.uiState.value);

    useEffect(() => {
        // Create the observer
        const flowObserver = new com.example.util.FlowObserver(viewModel.uiState);

        flowObserver.start((newState: AuthUiState) => {
            setState(newState);
        });

        // Cleanup on unmount
        return () => {
            flowObserver.stop();
        };
    }, [viewModel]);

    return {
        state,
        login: (email: string, password: string) => viewModel.onLogin(email, password),
        resetState: () => viewModel.resetState()
    };
};

คอมโพเนนต์หน้าของ Next.js

เอาต์พุต Kotlin/JS รันใน JavaScript runtime ถ้าลอจิก KMP พยายามเข้าถึง API ที่เฉพาะเบราว์เซอร์ระหว่างรอบ server-side render แอปจะ crash

// app-web/src/app/login/page.tsx

'use client'; // Mandatory for KMP integration

import { useAuthViewModel } from '@/hooks/useAuthViewModel';
import { useState } from 'react';
import { com } from 'auth-shared';

export default function LoginPage() {
    const { state, login } = useAuthViewModel();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    // Type guards for Kotlin Sealed Classes in JS
    const isLoading = state instanceof com.example.auth.presentation.AuthUiState.Loading;
    const isSuccess = (s: any): s is { user: { displayName: string } } => {
        return s instanceof com.example.auth.presentation.AuthUiState.Success;
    };
    const isError = (s: any): s is { message: string } => {
        return s instanceof com.example.auth.presentation.AuthUiState.Error;
    };

    if (isSuccess(state)) {
        return (
            <main className="flex min-h-screen flex-col items-center justify-center p-24">
                <h1 className="text-4xl font-bold">
                    Welcome, {state.user.displayName}!
                </h1>
            </main>
        );
    }

    return (
        <main className="flex min-h-screen flex-col items-center justify-center p-24">
            <form 
                className="flex flex-col gap-4 w-full max-w-md"
                onSubmit={(e) => {
                    e.preventDefault();
                    login(email, password);
                }}
            >
                <input
                    type="email"
                    placeholder="Email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="px-4 py-2 border rounded"
                />
                <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="px-4 py-2 border rounded"
                />
                <button
                    type="submit"
                    disabled={isLoading}
                    className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
                >
                    {isLoading ? 'Loading...' : 'Login'}
                </button>
                
                {isError(state) && (
                    <p className="text-red-500 text-sm">{state.message}</p>
                )}
            </form>
        </main>
    );
}

จะจัดการความปลอดภัยของ SSR กับ KMP และ Next.js อย่างไร

เมื่อเชื่อม KMP กับ Next.js คุณต้องคิดถึงความเข้ากันของ server-side rendering

ไดเรกทีฟ ‘use client’ คอมโพเนนต์ทุกตัวที่ใช้ hook ของ KMP ต้องติด 'use client' เพื่อให้รันในบริบทเบราว์เซอร์เป็นหลัก

Lazy Loading ใน jsMain ให้แน่ใจว่าการเข้าถึง browser API ทำแบบ lazy หรือมีตัวกันด้วยการตรวจ typeof window !== 'undefined'

Dynamic Imports สำหรับโมดูล KMP ที่หนัก ใช้ next/dynamic พร้อม ssr: false เพื่อปิด server-rendering ของต้นไม้คอมโพเนนต์นั้น

ข้อแลกเปลี่ยน

ฟีเจอร์

React Native / Flutter

KMP (Headless)

การวิเคราะห์

การเรนเดอร์ UI

เอนจินเอง / สะพาน native

UI ของแพลตฟอร์ม

UI อยู่บน Compose, SwiftUI และ React

การแชร์โค้ด

UI + ลอจิก

เฉพาะลอจิก

ส่วนที่แชร์คือ domain, data และ ViewModel

การรองรับเว็บ

Canvas (Flutter) หรือ DOM (RN Web)

DOM แบบ native (React)

KMP ใช้ฟีเจอร์มาตรฐานของ Next.js ได้

ประสิทธิภาพ

overhead ของสะพาน

JVM บน Android, ไบนารี native บน iOS

Android คอมไพล์เป็น JVM bytecode iOS คอมไพล์เป็นไบนารี native

ความซับซ้อนของ build pipeline การดูแลบิลด์ Gradle ที่ออก Android AAR, iOS Framework และแพ็กเกจ NPM ให้ถูกต้องนั้นซับซ้อน ต้องใช้ความรู้ platform engineering การดีบัก dependency ของ Gradle task ข้ามสามระบบนิเวศไม่ใช่เรื่องเล็ก

ต้นทุนการสลับบริบทในหัว นักพัฒนาต้องเข้าใจ Kotlin สำหรับลอจิก, Swift สำหรับ UI ของ iOS และ TypeScript สำหรับ UI ของเว็บ นี่คือภาระทางความคิดที่สูงกว่าสแต็ก TypeScript ล้วน UI อยู่บน SwiftUI, Compose และ React

ขนาดบันเดิล Kotlin/JS แม้มี Dead Code Elimination การใส่ Kotlin Standard Library และ Coroutines ในบันเดิล JS ก็เพิ่มน้ำหนัก ยอมรับได้สำหรับเว็บแอปที่ซับซ้อน แต่อาจมากไปสำหรับแลนดิ้งเพจเรียบง่าย

แรงเสียดทานของ interop SKIE ปรับปรุง interop ของ iOS และ @JsExport ครอบคลุมการ export ฝั่งเว็บ กรณีขอบยังเหลือ generic ของ Kotlin, type Long และ sealed class ต้องจัดการเฉพาะทางเพื่อให้รู้สึกเป็นธรรมชาติใน Swift และ TypeScript

เขียนโค้ดให้สนุก!

David Cruz
davthecoder.com

Share:Compartir:แชร์:

CommentsComentariosความคิดเห็น

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…