Skip to content

ภาษา

EnglishEestiEspañolไทย

ผมใช้ AI ช่วยเขียนและตรวจแก้ข้อความเหล่านี้ จึงอาจมีคำสะกดผิดหรือข้อผิดพลาด หากพบ กรุณาแจ้งที่ [email protected]

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

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

Kotlin Multiplatform

โดย David Cruz Anaya, วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

อัปเดตเมื่อ 11 กรกฎาคม 2026อ่าน 6 นาที

Android · Kotlin · Kotlin Multiplatform · iOS · Next.js · Clean Architecture · Mobile Development

โค้ดเบสเดียวของ 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

แชร์: