Upgrade to Pro — share decks privately, control downloads, hide ads and more …

KMP 經驗分享

Avatar for Hokila Jan Hokila Jan
June 19, 2025
40

KMP 經驗分享

Kotlin Multiplatform

大概使用半年,只簡單用在 api 層,與 data model。
結合我看到別人的用法,來介紹一下我覺得 KMP 的好處。

Avatar for Hokila Jan

Hokila Jan

June 19, 2025
Tweet

Transcript

  1. 你的 app 有 bug •是你寫的 bug •還是 iOS 的 bug

    •還是 Android 的 bug •還是 flutter 的 bug Prompt: 中年光頭⼤叔,抓狂⼀族風格,「你的 code 有 bug」,電腦要顯⽰ bug
  2. 業界案例 Wantedly • https://www.youtube.com/watch?v=85JmR_Pv6_M • from iOSDC 2024 • 徹底擁抱

    KMP • api requst/response • data model parser • viewModel -> 他們叫 Reactor • ⽤ swiftUI 寫 UI • 除了 UI 能⽤的都⽤了,可能下⼀步就是 Compose Multiplatform 了
  3. 我現在使⽤的 • api requst/response • data model parser. <—— 今天講這部分

    會後補充:我真的沒有⽤ KMP 接 UI code,不要再問我 UI 問題了
  4. 常⾒衝突 欄位名稱 類型 是否必填 id integer ✅ Required value string

    ❌ Optional name string ✅ Required description string ❌ Optional
  5. { "items": [ { "id": 1, "value": "A001", "name": "Item

    One", "description": "This is the first item." }, { "id": 2, "value": "B002", "name": "Item Two", "description": "This is the second item." }, { "id": 3, "value": "C003", "name": "Item Three", "description": "This is the third item." } ] } struct ItemResponse: Codable { let items: [Item] } struct Item: Codable { let id: Int let value: String? let name: String let description: String? } struct Item: Codable { let id: Int let value: String? = "" let name: String let description: String? } 要不要⽤ default value?
  6. { "items": [ { "id": 1, "value": "A001", "name": "Item

    One", "description": "This is the first item." }, { "id": 2, "value": "B002", "description": "This is the second item." }, { "id": 3, "value": "C003", "name": "Item Three", "description": "This is the third item." } ] } 沒有 name parse fail 還是 drop item?
  7. app 架構 • KMP 是另⼀個repo,包成 framework • Xcode add shell

    script,先⽤ gradle 包出 arm framework,再打包成 xcframework • 使⽤ SPM 管理,或者直接上⾯包好的⽤ xcframework 也可以 • 幾乎沒有 dependency
  8. 好處 • 對 Android ⼯程師來說:本來就是在寫 kotlin,沒有語⾔障 礙。 • 對 iOS

    ⼯程師來說,api 抄就對了,kotlin 跟 swift 有 8 成像, 就算不會還能問 AI • 有 api spec 就能開⼯。 • 對 QA 來說,兩邊⾏為⼀定⼀樣,同⽣共死 • 未來要淘汰 KMP 的話,可以逐 api 替換
  9. 會後QA補充 • KMP 回傳的物件都是 kotlin 的 data model,swift 可以直接⽤,有 時候我們會再轉成

    UI ⽤的 model,轉完後當然就全都是 swift。有 時候不想轉這麼多,就寫 extension 幫這個 model 增加欄位。 • 這個 framework 裡⾯有很多⼩ class,彼此間幾乎沒有關係,⼯作很 單⼀比如說轉成統⼀的 Kotlin API Request,我們轉成 URLRequest 以後,打 API 拿到 response 再⽤ KMP 轉成 data model,parse 的商 業邏輯都在 KMP 裡。要怎麼顯⽰ UI 都在 native code 裡。 • zonble:kotlin 這種東西,半個⽉就學會了