Skip to content

Kotlin Multiplatform으로 풀스택 애플리케이션 구축하기

코드 예제: full-stack-task-manager

사용된 플러그인: Routing라우팅은 서버 애플리케이션에서 들어오는 요청을 처리하기 위한 핵심 플러그인입니다., kotlinx.serialization, Content NegotiationContentNegotiation 플러그인은 두 가지 주요 목적을 수행합니다. 클라이언트와 서버 간의 미디어 유형 협상, 그리고 특정 형식으로 콘텐츠를 직렬화/역직렬화하는 것입니다., Compose Multiplatform, Kotlin Multiplatform

이 문서에서는 매끄러운 데이터 처리를 위해 Ktor를 활용하면서 Android, iOS, 웹(Web), 데스크톱(Desktop) 플랫폼에서 실행되는 Kotlin 풀스택 애플리케이션을 개발하는 방법을 알아봅니다.

이 튜토리얼을 마치면 다음 작업을 수행할 수 있게 됩니다:

  • Kotlin Multiplatform을 사용해 풀스택 애플리케이션을 생성합니다.
  • IntelliJ IDEA로 생성된 프로젝트의 구조를 이해합니다.
  • Ktor 서비스를 호출하는 Compose Multiplatform 클라이언트를 생성합니다.
  • 설계의 여러 계층에 걸쳐 공통 타입을 재사용합니다.
  • 멀티플랫폼 라이브러리를 올바르게 포함하고 구성합니다.

이전 튜토리얼들에서는 작업 관리자(Task Manager) 예제를 사용하여 요청을 처리하고태스크 관리자(Task Manager) 애플리케이션을 빌드하며 Kotlin 및 Ktor를 통한 라우팅, 요청 처리, 파라미터 기초를 학습합니다., RESTful API를 생성하고Kotlin과 Ktor를 사용하여 백엔드 서비스를 구축하는 방법을 배우며, JSON을 생성하는 RESTful API 예제를 다룹니다., Exposed를 사용해 데이터베이스를 통합Exposed SQL 라이브러리를 사용하여 Ktor 서비스를 데이터베이스 리포지토리에 연결하는 프로세스를 알아봅니다.했습니다. 이때는 Ktor의 기본 개념 학습에 집중할 수 있도록 클라이언트 애플리케이션을 최대한 단순하게 유지했습니다.

이제 표시할 데이터를 가져오기 위해 Ktor 서비스를 사용하면서 Android, iOS, 웹, 데스크톱 플랫폼을 대상으로 하는 클라이언트를 빌드하게 됩니다. 가능한 한 클라이언트와 서버 간에 데이터 타입을 공유하여 개발 속도를 높이고 오류 발생 가능성을 줄일 것입니다.

사전 요구 사항

이전 문서들과 마찬가지로 IntelliJ IDEA를 IDE로 사용합니다. 환경을 설치하고 구성하려면 Kotlin Multiplatform 빠른 시작(quickstart) 을 참고하세요.

Compose Multiplatform을 처음 사용하는 경우, 이 튜토리얼을 시작하기 전에 Compose Multiplatform 시작하기 튜토리얼을 먼저 완료하는 것을 권장합니다. 작업의 복잡도를 낮추기 위해 단일 클라이언트 플랫폼에만 집중해도 좋습니다. 예를 들어 iOS를 사용해 본 적이 없다면 데스크톱이나 Android 개발에 집중하는 것이 현명할 수 있습니다.

새 프로젝트 생성

Ktor 프로젝트 생성기 대신 IntelliJ IDEA의 Kotlin Multiplatform 프로젝트 마법사를 사용합니다. 이를 통해 클라이언트와 서비스로 확장할 수 있는 기본 멀티플랫폼 프로젝트가 생성됩니다. 클라이언트는 SwiftUI와 같은 네이티브 UI 라이브러리를 사용할 수도 있지만, 이 튜토리얼에서는 Compose Multiplatform을 사용하여 모든 플랫폼을 위한 공유 UI를 생성합니다.

  1. IntelliJ IDEA를 실행합니다.
  2. IntelliJ IDEA에서 File | New | Project 를 선택합니다.
  3. 왼쪽 패널에서 Kotlin Multiplatform 을 선택합니다.
  4. New Project 창에서 다음 필드를 지정합니다:
    • Name : full-stack-task-manager
    • Project ID : com.example.ktor
  5. 대상 플랫폼으로 Android , Desktop , Web , Server 를 선택합니다.

  6. Mac을 사용하는 경우 iOS 도 함께 선택합니다. 이때 Share UI 옵션이 선택되어 있는지 확인하세요. Kotlin Multiplatform 마법사 설정

  7. Create 버튼을 클릭하고 IDE가 프로젝트를 생성하고 가져올 때까지 기다립니다.

서비스 실행

  1. IntelliJ IDEA에서 ApplicationKt 실행 구성을 선택합니다. Run & Debug 창
  2. Run 버튼 (IntelliJ IDEA 실행 아이콘) 을 클릭하여 구성을 실행합니다.

    Run 도구 창에 새 탭이 열립니다.

  3. http://0.0.0.0:8080/으로 이동하여 애플리케이션을 엽니다. 브라우저에 Ktor가 보낸 메시지가 표시되어야 합니다. Ktor 서버 브라우저 응답

프로젝트 살펴보기

server 폴더는 프로젝트 내 3개의 Kotlin 모듈 중 하나입니다. 나머지 둘은 core 와 app 입니다.

server 모듈의 구조는 Ktor Project Generator에서 생성된 구조와 매우 유사합니다. 플러그인 및 의존성을 선언하는 전용 빌드 파일과 Ktor 서비스를 빌드하고 시작하는 코드가 포함된 소스 세트가 있습니다:

Kotlin Multiplatform 프로젝트의 server 폴더 내용

Application.kt 파일의 라우팅 명령을 살펴보면 sayHello() 함수가 호출되는 것을 볼 수 있습니다:

kotlin
fun Application.module() {
    routing {
        get("/") {
            call.respondText(sayHello("Ktor"))
        }
    }
}

sayHello() 함수는 core 모듈에 정의되어 있습니다. 이곳은 서버와 모든 다양한 클라이언트 플랫폼 간에 공유될 공통 코드를 두는 곳입니다.

app/shared/src/commonMain 모듈 내의 Greeting.kt 파일을 열어보면 그곳에서도 sayHello() 함수가 사용되고 있음을 확인할 수 있습니다:

kotlin
class Greeting {
    private val platform = getPlatform()

    fun greet(): String {
        return sayHello(platform.name)
    }
}

app 모듈에는 다음 서브모듈들이 포함되어 있습니다:

  • androidApp, desktopApp, iosApp, webApp 서브모듈은 각각 Android, 데스크톱, iOS, 웹 클라이언트 앱을 위한 플랫폼별 코드를 포함합니다. 현재는 이 클라이언트 앱들 중 어느 것도 Ktor 서비스에 연결되어 있지 않습니다.
  • shared 서브모듈에는 클라이언트를 제공하고자 하는 각 플랫폼에 대한 소스 세트가 포함되어 있습니다. 이는 commonMain 내에 선언된 타입들이 대상 플랫폼마다 달라지는 기능을 필요로 하기 때문입니다.

    예를 들어 Greeting 타입에서 현재 플랫폼의 이름은 expect 및 actual 선언을 통해 플랫폼별 API를 사용하여 검색됩니다.

    shared 서브모듈의 commonMain 소스 세트에서는 getPlatform() 함수가 expect 키워드로 선언되어 있습니다:

    kotlin
    package com.example.ktor
    
    interface Platform {
        val name: String
    }
    
    expect fun getPlatform(): Platform

    그런 다음 각 대상 플랫폼은 아래와 같이 getPlatform() 함수의 actual 선언을 제공합니다:

    kotlin
    package com.example.ktor
    
    import platform.UIKit.UIDevice
    
    class IOSPlatform : Platform {
        override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
    }
    
    actual fun getPlatform(): Platform = IOSPlatform()
    kotlin
    package com.example.ktor
    
    import android.os.Build
    
    class AndroidPlatform : Platform {
        override val name: String = "Android ${Build.VERSION.SDK_INT}"
    }
    
    actual fun getPlatform(): Platform = AndroidPlatform()
    kotlin
    package com.example.ktor
    
    class JVMPlatform : Platform {
        override val name: String = "Java ${System.getProperty("java.version")}"
    }
    
    actual fun getPlatform(): Platform = JVMPlatform()
    kotlin
    package com.example.ktor
    
    class WasmPlatform : Platform {
        override val name: String = "Web with Kotlin/Wasm"
    }
    
    actual fun getPlatform(): Platform = WasmPlatform()

클라이언트 애플리케이션 실행

대상 플랫폼의 실행 구성을 실행하여 클라이언트 애플리케이션을 구동할 수 있습니다. iOS Simulator에서 애플리케이션을 실행하려면 아래 단계를 따르세요:

  1. IntelliJ IDEA에서 iosApp 실행 구성과 시뮬레이션 디바이스를 선택합니다. Run & Debug 창
  2. Run 버튼 (IntelliJ IDEA 실행 아이콘) 을 클릭하여 구성을 실행합니다.
  3. iOS 앱을 실행하면 내부적으로 Xcode로 빌드된 후 iOS Simulator에서 실행됩니다. 앱에는 클릭 시 이미지를 토글하는 버튼이 표시됩니다. iOS Simulator에서 앱 실행하기

    버튼을 처음 누르면 버튼 텍스트에 현재 플랫폼의 세부 정보가 추가됩니다. 이를 구현한 코드는 app/shared/src/commonMain/kotlin/com/example/ktor/App.kt 에서 찾을 수 있습니다:

    kotlin
    @Composable
    @Preview
    fun App() {
        MaterialTheme {
            var showContent by remember { mutableStateOf(false) }
            Column(
                modifier = Modifier
                    .background(MaterialTheme.colorScheme.primaryContainer)
                    .safeContentPadding()
                    .fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = { showContent = !showContent }) {
                    Text("Click me!")
                }
                AnimatedVisibility(showContent) {
                    val greeting = remember { Greeting().greet() }
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        Image(painterResource(Res.drawable.compose_multiplatform), null)
                        Text("Compose: $greeting")
                    }
                }
            }
        }
    }

    이것은 컴포저블(composable) 함수이며, 이 문서의 뒷부분에서 수정할 예정입니다. 지금은 이 함수가 UI를 표시하고 공통 Platform 인터페이스를 구현한 플랫폼별 클래스를 사용하는 공유 Greeting 타입을 활용하고 있다는 점만 이해하면 충분합니다.

이제 생성된 프로젝트의 구조를 이해했으므로, 작업 관리자 기능을 단계적으로 추가할 수 있습니다.

모델 타입 추가

먼저 모델 타입을 추가하고 클라이언트와 서버 모두에서 접근할 수 있도록 설정합니다.

  1. gradle/libs.versions.toml 로 이동하여 다음 kotlinx.serialization 의존성을 정의합니다:
    toml
    [versions]
    kotlinx-serialization-json = "1.11.0"
    
    [libraries]
    kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization-json" }
    
    [plugins]
    kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
  2. core/build.gradle.kts 로 이동하여 serialization 플러그인을 추가합니다:

    kotlin
    plugins {
        //...
        alias(libs.plugins.kotlinSerialization)
    }
  3. 동일한 파일에서 commonMain 소스 세트에 새 의존성을 추가합니다:

    kotlin
    sourceSets {
        commonMain.dependencies {
            // put your Multiplatform dependencies here
            implementation(libs.kotlinx.serialization.json)
        }
        //...
    }
  4. IntelliJ IDEA에서 Build | Sync Project with Gradle Files 를 선택하여 변경 사항을 적용합니다. Gradle import가 완료되면 Task.kt 파일이 정상적으로 컴파일될 것입니다.
  5. core/src/commonMain/kotlin/com/example/ktor 로 이동하여 model 이라는 새 패키지를 만듭니다.
  6. 새 패키지 안에 Task.kt 라는 새 파일을 만듭니다.
  7. 우선순위를 나타내는 enum과 작업을 나타내는 클래스를 추가합니다. Task 클래스에는 kotlinx.serialization 라이브러리의 Serializable 타입으로 어노테이션을 추가합니다:

    kotlin
    package com.example.ktor.model
    
    import kotlinx.serialization.Serializable
    
    enum class Priority {
        Low, Medium, High, Vital
    }
    
    @Serializable
    data class Task(
        val name: String,
        val description: String,
        val priority: Priority
    )

서버 생성

다음 단계는 작업 관리자를 위한 서버 구현을 작성하는 것입니다.

  1. server/src/main/kotlin/com/example/ktor 폴더로 이동하여 model 이라는 하위 패키지를 만듭니다.
  2. 이 패키지 안에 새 TaskRepository.kt 파일을 만들고 리포지토리를 위한 다음 인터페이스를 추가합니다:

    kotlin
    package com.example.ktor.model
    
    interface TaskRepository {
        fun allTasks(): List<Task>
        fun tasksByPriority(priority: Priority): List<Task>
        fun taskByName(name: String): Task?
        fun addOrUpdateTask(task: Task)
        fun removeTask(name: String): Boolean
    }
  3. 동일한 패키지에 다음 클래스가 포함된 새 파일 InMemoryTaskRepository.kt 를 생성합니다:

    kotlin
    package com.example.ktor.model
    
    class InMemoryTaskRepository : TaskRepository {
        private var tasks = listOf(
            Task("Cleaning", "Clean the house", Priority.Low),
            Task("Gardening", "Mow the lawn", Priority.Medium),
            Task("Shopping", "Buy the groceries", Priority.High),
            Task("Painting", "Paint the fence", Priority.Low),
            Task("Cooking", "Cook the dinner", Priority.Medium),
            Task("Relaxing", "Take a walk", Priority.High),
            Task("Exercising", "Go to the gym", Priority.Low),
            Task("Learning", "Read a book", Priority.Medium),
            Task("Snoozing", "Go for a nap", Priority.High),
            Task("Socializing", "Go to a party", Priority.High)
        )
    
        override fun allTasks(): List<Task> = tasks
    
        override fun tasksByPriority(priority: Priority) = tasks.filter {
            it.priority == priority
        }
    
        override fun taskByName(name: String) = tasks.find {
            it.name.equals(name, ignoreCase = true)
        }
    
        override fun addOrUpdateTask(task: Task) {
            var notFound = true
    
            tasks = tasks.map {
                if (it.name == task.name) {
                    notFound = false
                    task
                } else {
                    it
                }
            }
            if (notFound) {
                tasks = tasks.plus(task)
            }
        }
    
        override fun removeTask(name: String): Boolean {
            val oldTasks = tasks
            tasks = tasks.filterNot { it.name == name }
            return oldTasks.size > tasks.size
        }
    }
  4. server/src/main/kotlin/.../Application.kt 로 이동하여 기존 코드를 아래 구현으로 바꿉니다:

    kotlin
    package com.example.ktor
    
    import com.example.ktor.model.InMemoryTaskRepository
    import com.example.ktor.model.Priority
    import com.example.ktor.model.Task
    import io.ktor.http.*
    import io.ktor.serialization.*
    import io.ktor.serialization.kotlinx.json.*
    import io.ktor.server.application.*
    import io.ktor.server.engine.*
    import io.ktor.server.netty.*
    import io.ktor.server.plugins.contentnegotiation.*
    import io.ktor.server.plugins.cors.routing.*
    import io.ktor.server.request.*
    import io.ktor.server.response.*
    import io.ktor.server.routing.*
    
    fun main() {
        embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
            .start(wait = true)
    }
    
    fun Application.module() {
        install(ContentNegotiation) {
            json()
        }
        install(CORS) {
            allowHeader(HttpHeaders.ContentType)
            allowMethod(HttpMethod.Delete)
            // For ease of demonstration we allow any connections.
            // Don't do this in production.
            anyHost()
        }
        val repository = InMemoryTaskRepository()
    
        routing {
            route("/tasks") {
                get {
                    val tasks = repository.allTasks()
                    call.respond(tasks)
                }
                get("/byName/{taskName}") {
                    val name = call.parameters["taskName"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    val task = repository.taskByName(name)
                    if (task == null) {
                        call.respond(HttpStatusCode.NotFound)
                        return@get
                    }
                    call.respond(task)
                }
                get("/byPriority/{priority}") {
                    val priorityAsText = call.parameters["priority"]
                    if (priorityAsText == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    try {
                        val priority = Priority.valueOf(priorityAsText)
                        val tasks = repository.tasksByPriority(priority)
    
    
                        if (tasks.isEmpty()) {
                            call.respond(HttpStatusCode.NotFound)
                            return@get
                        }
                        call.respond(tasks)
                    } catch (ex: IllegalArgumentException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
                post {
                    try {
                        val task = call.receive<Task>()
                        repository.addOrUpdateTask(task)
                        call.respond(HttpStatusCode.NoContent)
                    } catch (ex: IllegalStateException) {
                        call.respond(HttpStatusCode.BadRequest)
                    } catch (ex: JsonConvertException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
                delete("/{taskName}") {
                    val name = call.parameters["taskName"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@delete
                    }
                    if (repository.removeTask(name)) {
                        call.respond(HttpStatusCode.NoContent)
                    } else {
                        call.respond(HttpStatusCode.NotFound)
                    }
                }
            }
        }
    }

    이 구현은 단순성을 위해 모든 라우팅 코드를 Application.module() 함수 안에 배치했다는 점을 제외하면 이전 튜토리얼과 매우 유사합니다.

    이 코드를 입력하고 import를 추가하면 여러 컴파일러 오류가 발생하는데, 이는 웹 클라이언트와의 통신을 위한 CORS필수 의존성: io.ktor:ktor-server-cors 플러그인을 포함하여 의존성으로 추가해야 하는 여러 Ktor 플러그인을 코드가 사용하고 있기 때문입니다.

  5. settings.gradle.kts를 열고 Ktor 버전 카탈로그를 가져옵니다:
    kotlin
    dependencyResolutionManagement {
        versionCatalogs {
            create("ktorLibs").from("io.ktor:ktor-version-catalog:3.6.1")
        }
    }
  6. 서버 모듈 빌드 파일( server/build.gradle.kts )을 열고 다음 의존성을 추가합니다:

    kotlin
    dependencies {
        //...
        implementation(ktorLibs.serialization.kotlinx.json)
        implementation(ktorLibs.server.contentNegotiation)
        implementation(ktorLibs.server.cors)
    }
  7. 다시 한 번 메인 메뉴에서 Build | Sync Project with Gradle Files를 선택합니다. 가져오기가 완료되면 ContentNegotiation 타입과 json() 함수에 대한 import가 올바르게 작동하는 것을 확인할 수 있습니다.
  8. 서버를 다시 실행합니다. 브라우저에서 해당 라우트에 접근할 수 있어야 합니다.
  9. 및 으로 이동하여 JSON 형식의 작업 데이터가 포함된 서버 응답을 확인합니다. 브라우저에서의 서버 응답

클라이언트 생성

클라이언트가 서버에 접근할 수 있도록 하려면 Ktor Client를 포함해야 합니다. 여기에는 세 가지 유형의 의존성이 필요합니다:

  • Ktor Client의 핵심 기능.
  • 네트워킹을 처리하기 위한 플랫폼별 엔진.
  • 콘텐츠 협상 및 직렬화 지원.
  1. app/shared/build.gradle.kts 로 이동하여 다음 의존성을 추가합니다:
    kotlin
    kotlin {
        //...
        sourceSets {
            androidMain.dependencies {
                //...
                implementation(ktorLibs.client.android)
            }
            commonMain.dependencies {
                //...
                implementation(ktorLibs.client.core)
                implementation(ktorLibs.client.contentNegotiation)
                implementation(ktorLibs.serialization.kotlinx.json)
            }
            jvmMain.dependencies {
                implementation(ktorLibs.client.cio)
            }
            iosMain.dependencies {
                implementation(ktorLibs.client.darwin)
            }
            wasmJsMain.dependencies {
                implementation(ktorLibs.client.js)
            }
        }
    }

    이 작업이 완료되면 클라이언트가 Ktor Client를 감싸는 얇은 래퍼 역할을 할 TaskApi 타입을 추가할 수 있습니다.

  2. 메인 메뉴에서 Build | Sync Project with Gradle Files를 선택하여 빌드 파일의 변경 사항을 반영합니다.
  3. app/shared/src/commonMain/kotlin/com/example/ktor 로 이동하여 network 라는 새 패키지를 만듭니다.
  4. 새 패키지 안에 클라이언트 구성을 위한 새 HttpClientManager.kt 파일을 만듭니다:

    kotlin
    package com.example.ktor.network
    
    import io.ktor.client.HttpClient
    import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
    import io.ktor.client.plugins.defaultRequest
    import io.ktor.serialization.kotlinx.json.json
    import kotlinx.serialization.json.Json
    
    fun createHttpClient() = HttpClient {
        install(ContentNegotiation) {
            json(Json {
                encodeDefaults = true
                isLenient = true
                coerceInputValues = true
                ignoreUnknownKeys = true
            })
        }
        defaultRequest {
            host = "1.2.3.4" // Replace with the IP address of your current machine.
            port = 8080
        }
    }

    1.2.3.4를 현재 컴퓨터의 IP 주소로 바꿉니다. Android 가상 기기(AVD)나 iOS Simulator에서 실행되는 코드에서는 0.0.0.0 또는 localhost로의 호출이 불가능합니다.

    IP 주소 확인 방법:

    모바일 시뮬레이터는 localhost에 접근할 수 없으므로 실제 컴퓨터의 IP 주소가 필요합니다. IP 주소를 확인하려면 다음 명령 중 하나를 실행하세요:

    • macOS: ifconfig | grep "inet " | grep -v 127.0.0.1
    • Linux: hostname -I | awk '{print $1}'
    • Windows: ipconfig 실행 후 "IPv4 주소" 확인
  5. 동일한 app/shared/.../network 패키지 안에 다음 구현을 포함하는 새 TaskApi.kt 파일을 만듭니다:

    kotlin
    package com.example.ktor.network
    
    import com.example.ktor.model.Task
    import io.ktor.client.HttpClient
    import io.ktor.client.call.body
    import io.ktor.client.request.delete
    import io.ktor.client.request.get
    import io.ktor.client.request.post
    import io.ktor.client.request.setBody
    import io.ktor.http.ContentType
    import io.ktor.http.contentType
    
    class TaskApi(private val httpClient: HttpClient) {
    
        suspend fun getAllTasks(): List<Task> {
            return httpClient.get("tasks").body()
        }
    
        suspend fun removeTask(task: Task) {
            httpClient.delete("tasks/${task.name}")
        }
    
        suspend fun updateTask(task: Task) {
            httpClient.post("tasks") {
                contentType(ContentType.Application.Json)
                setBody(task)
            }
        }
    }
  6. app/shared/.../App.kt 로 이동하여 코드를 아래 구현으로 교체합니다. 이 코드는 TaskApi 타입을 사용하여 서버에서 작업 목록을 가져온 다음, 각 작업의 이름을 컬럼에 표시합니다:

    kotlin
    package com.example.ktor
    
    import com.example.ktor.network.TaskApi
    import com.example.ktor.network.createHttpClient
    import com.example.ktor.model.Task
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.safeContentPadding
    import androidx.compose.material3.Button
    import androidx.compose.material3.MaterialTheme
    import androidx.compose.material3.Text
    import androidx.compose.runtime.*
    import androidx.compose.ui.Alignment
    import androidx.compose.ui.Modifier
    import kotlinx.coroutines.launch
    
    @Composable
    fun App() {
        MaterialTheme {
            val httpClient = createHttpClient()
            val taskApi = remember { TaskApi(httpClient) }
            val tasks = remember { mutableStateOf(emptyList<Task>()) }
            val scope = rememberCoroutineScope()
    
            Column(
                modifier = Modifier
                    .safeContentPadding()
                    .fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                    scope.launch {
                        tasks.value = taskApi.getAllTasks()
                    }
                }) {
                    Text("Fetch Tasks")
                }
                for (task in tasks.value) {
                    Text(task.name)
                }
            }
        }
    }
  7. 서버가 실행 중인 상태에서 iosApp 실행 구성을 실행하여 iOS 애플리케이션을 테스트합니다.

  8. Fetch Tasks 버튼을 클릭하여 작업 목록을 표시합니다: iOS에서 실행 중인 앱

    이 데모에서는 명확한 설명을 위해 과정을 단순화했습니다. 실제 애플리케이션에서는 암호화되지 않은 데이터를 네트워크를 통해 전송하지 않도록 주의해야 합니다.
  9. Android 플랫폼에서는 애플리케이션에 명시적으로 네트워킹 권한을 부여하고 일반 텍스트(cleartext) 송수신을 허용해야 합니다. 이러한 권한을 활성화하려면 app/androidApp/src/main/AndroidManifest.xml 을 열고 다음 설정을 추가합니다:

    xml
    <manifest>
        ...
        <application
                android:usesCleartextTraffic="true">
        ...
        ...
        </application>
        <uses-permission android:name="android.permission.INTERNET"/>
    </manifest>
  10. app.androidApp 실행 구성을 사용하여 Android 애플리케이션을 실행합니다. 이제 Android 클라이언트도 정상적으로 실행되는 것을 확인할 수 있습니다: Android에서 실행 중인 앱

  11. 데스크톱 클라이언트의 경우, 창의 크기와 제목을 지정합니다. app/desktopApp/src/.../main.kt 파일을 열고 title을 변경하고 state 프로퍼티를 설정하여 코드를 수정합니다:

    kotlin
    package com.example.ktor
    
    import androidx.compose.ui.unit.DpSize
    import androidx.compose.ui.unit.dp
    import androidx.compose.ui.window.Window
    import androidx.compose.ui.window.WindowPosition
    import androidx.compose.ui.window.WindowState
    import androidx.compose.ui.window.application
    
    fun main() = application {
        val state = WindowState(
            size = DpSize(400.dp, 600.dp),
            position = WindowPosition(200.dp, 100.dp)
        )
        Window(
            title = "Task Manager (Desktop)",
            state = state,
            onCloseRequest = ::exitApplication,
        ) {
            App()
        }
    }
  12. app [hot] 🔥 실행 구성을 사용하여 데스크톱 애플리케이션을 실행합니다: 데스크톱에서 실행 중인 앱

  13. 다음 실행 구성 중 하나를 사용하여 웹 클라이언트를 실행합니다:

    • app [js]: Kotlin/JS 애플리케이션을 실행합니다.
    • app [wasmJs]: Kotlin/Wasm 애플리케이션을 실행합니다.
    웹에서 실행 중인 앱

UI 개선

이제 클라이언트가 서버와 통신하고 있지만, 아직 UI가 미흡합니다.

  1. app/shared/src/commonMain/.../ktor 에 있는 App.kt 파일을 열고 기존 App을 아래의 App 및 TaskCard 컴포저블로 교체합니다:

    fun App() { {...}
    kotlin
    package com.example.ktor
    
    import com.example.ktor.network.TaskApi
    import com.example.ktor.model.Priority
    import com.example.ktor.model.Task
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.Row
    import androidx.compose.foundation.layout.Spacer
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.foundation.layout.safeContentPadding
    import androidx.compose.foundation.layout.width
    import androidx.compose.foundation.lazy.LazyColumn
    import androidx.compose.foundation.lazy.items
    import androidx.compose.foundation.shape.CornerSize
    import androidx.compose.foundation.shape.RoundedCornerShape
    import androidx.compose.material3.Card
    import androidx.compose.material3.MaterialTheme
    import androidx.compose.material3.OutlinedButton
    import androidx.compose.material3.Text
    import androidx.compose.runtime.*
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.text.font.FontWeight
    import androidx.compose.ui.unit.dp
    import androidx.compose.ui.unit.sp
    import com.example.ktor.network.createHttpClient
    import kotlinx.coroutines.launch
    
    @Composable
    fun App() {
        MaterialTheme {
            val httpClient = createHttpClient()
            val taskApi = remember { TaskApi(httpClient) }
            var tasks by remember { mutableStateOf(emptyList<Task>()) }
            val scope = rememberCoroutineScope()
    
            LaunchedEffect(Unit) {
                tasks = taskApi.getAllTasks()
            }
    
            LazyColumn(
                modifier = Modifier
                    .safeContentPadding()
                    .fillMaxSize()
            ) {
                items(tasks) { task ->
                    TaskCard(
                        task,
                        onDelete = {
                            scope.launch {
                                taskApi.removeTask(it)
                                tasks = taskApi.getAllTasks()
                            }
                        },
                        onUpdate = {
                        }
                    )
                }
            }
        }
    }
    
    @Composable
    fun TaskCard(
        task: Task,
        onDelete: (Task) -> Unit,
        onUpdate: (Task) -> Unit
    ) {
        fun pickWeight(priority: Priority) = when (priority) {
            Priority.Low -> FontWeight.SemiBold
            Priority.Medium -> FontWeight.Bold
            Priority.High, Priority.Vital -> FontWeight.ExtraBold
        }
    
        Card(
            modifier = Modifier.fillMaxWidth().padding(4.dp),
            shape = RoundedCornerShape(CornerSize(4.dp))
        ) {
            Column(modifier = Modifier.padding(10.dp)) {
                Text(
                    "${task.name}: ${task.description}",
                    fontSize = 20.sp,
                    fontWeight = pickWeight(task.priority)
                )
    
                Row {
                    OutlinedButton(onClick = { onDelete(task) }) {
                        Text("Delete")
                    }
                    Spacer(Modifier.width(8.dp))
                    OutlinedButton(onClick = { onUpdate(task) }) {
                        Text("Update")
                    }
                }
            }
        }
    }

    이 구현을 통해 클라이언트는 이제 기본적인 기능을 갖추게 됩니다.

    LaunchedEffect 타입을 사용하여 시작 시 모든 작업을 로드하고, LazyColumn 컴포저블을 통해 사용자가 작업을 스크롤하여 볼 수 있도록 합니다.

    마지막으로 별도의 TaskCard 컴포저블을 작성했으며, 이는 내부적으로 Card를 사용하여 각 Task의 세부 정보를 표시합니다. 작업을 삭제하고 업데이트할 수 있는 버튼도 추가되었습니다.

  2. 클라이언트 애플리케이션(예: Android 앱)을 다시 실행합니다. 이제 작업을 스크롤하고, 세부 정보를 확인하고, 삭제할 수 있습니다: 개선된 UI로 Android에서 실행 중인 앱

업데이트 기능 추가

클라이언트를 완성하기 위해 작업 세부 정보를 업데이트할 수 있는 기능을 추가합니다.

  1. app/shared/src/commonMain/.../ktor 에 있는 App.kt 파일로 이동합니다.
  2. 아래와 같이 UpdateTaskDialog 컴포저블과 필요한 import 문을 추가합니다:

    kotlin
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TextFieldDefaults
    import androidx.compose.ui.graphics.Color
    import androidx.compose.ui.window.Dialog
    
    @Composable
    fun UpdateTaskDialog(
        task: Task,
        onConfirm: (Task) -> Unit
    ) {
        var description by remember { mutableStateOf(task.description) }
        var priorityText by remember { mutableStateOf(task.priority.toString()) }
        val colors = TextFieldDefaults.colors(
            focusedTextColor = Color.Blue,
            focusedContainerColor = Color.White,
        )
    
        Dialog(onDismissRequest = {}) {
            Card(
                modifier = Modifier.fillMaxWidth().padding(4.dp),
                shape = RoundedCornerShape(CornerSize(4.dp))
            ) {
                Column(modifier = Modifier.padding(10.dp)) {
                    Text("Update ${task.name}", fontSize = 20.sp)
                    TextField(
                        value = description,
                        onValueChange = { description = it },
                        label = { Text("Description") },
                        colors = colors
                    )
                    TextField(
                        value = priorityText,
                        onValueChange = { priorityText = it },
                        label = { Text("Priority") },
                        colors = colors
                    )
                    OutlinedButton(onClick = {
                        val newTask = Task(
                            task.name,
                            description,
                            try {
                                Priority.valueOf(priorityText)
                            } catch (e: IllegalArgumentException) {
                                Priority.Low
                            }
                        )
                        onConfirm(newTask)
                    }) {
                        Text("Update")
                    }
                }
            }
        }
    }

    이 컴포저블은 대화상자(dialog box)로 Task의 세부 정보를 표시합니다. description과 priority는 수정할 수 있도록 TextField 컴포저블 내에 배치됩니다. 사용자가 업데이트 버튼을 누르면 onConfirm() 콜백이 트리거됩니다.

  3. 동일한 파일에서 App 컴포저블을 업데이트합니다:

    kotlin
    @Composable
    fun App() {
        MaterialTheme {
            val httpClient = createHttpClient()
            val taskApi = remember { TaskApi(httpClient) }
            var tasks by remember { mutableStateOf(emptyList<Task>()) }
            val scope = rememberCoroutineScope()
            var currentTask by remember { mutableStateOf<Task?>(null) }
    
            LaunchedEffect(Unit) {
                tasks = taskApi.getAllTasks()
            }
    
            if (currentTask != null) {
                UpdateTaskDialog(
                    currentTask!!,
                    onConfirm = {
                        scope.launch {
                            taskApi.updateTask(it)
                            tasks = taskApi.getAllTasks()
                        }
                        currentTask = null
                    }
                )
            }
    
            LazyColumn(modifier = Modifier
                .safeContentPadding()
                .fillMaxSize()
            ) {
                items(tasks) { task ->
                    TaskCard(
                        task,
                        onDelete = {
                            scope.launch {
                                taskApi.removeTask(it)
                                tasks = taskApi.getAllTasks()
                            }
                        },
                        onUpdate = {
                            currentTask = task
                        }
                    )
                }
            }
        }
    }

    선택된 현재 작업을 나타내는 추가 상태를 저장합니다. 이 값이 null이 아니면 UpdateTaskDialog 컴포저블을 호출하며, 이때 onConfirm() 콜백은 TaskApi를 사용하여 서버에 POST 요청을 보내도록 설정됩니다.

    마지막으로 TaskCard 컴포저블을 생성할 때 onUpdate() 콜백을 사용하여 currentTask 상태 변수를 설정합니다.

  4. 클라이언트 애플리케이션을 다시 실행합니다. 이제 버튼을 사용하여 각 작업의 세부 정보를 업데이트할 수 있습니다. Android에서 작업 삭제하기

다음 단계

이 문서에서는 Kotlin Multiplatform 애플리케이션의 맥락에서 Ktor를 사용하는 방법을 배웠습니다. 이제 다양한 플랫폼을 대상으로 하는 여러 서비스와 클라이언트가 포함된 프로젝트를 생성할 수 있습니다.

살펴본 바와 같이 코드 중복이나 낭비 없이 기능을 구축할 수 있습니다. 프로젝트의 모든 계층에서 필요한 타입은 core 멀티플랫폼 모듈에 둘 수 있습니다. 서비스에서만 필요한 기능은 server 모듈에 배치하고, 클라이언트에서만 필요한 기능은 app 모듈에 배치합니다.

이러한 형태의 개발에는 클라이언트와 서버 기술 모두에 대한 지식이 불가피하게 요구됩니다. 하지만 Kotlin Multiplatform 라이브러리와 Compose Multiplatform을 활용하면 새로 배워야 할 학습량을 최소화할 수 있습니다. 처음에는 단일 플랫폼에만 집중하더라도 애플리케이션에 대한 수요가 늘어남에 따라 다른 플랫폼을 쉽게 추가할 수 있습니다.