Yokan / rebuild
Course 1 8624561

08-kmp-cmp.md

.codex/skills/compose-kotlin-agent-skills/references/08-kmp-cmp.md

documentation / design asset359 lines
1# KMP / CMP — Kotlin Multiplatform & Compose Multiplatform23## Contents45- Shared module structure6- expect/actual pattern7- Shared ViewModel with KMP8- Shared domain layer9- Platform-specific UI vs shared Compose UI10- Ktor for networking11- Room vs SQLDelight for KMP persistence12- Real patterns from Authenticator app1314## Shared Module Structure1516From Authenticator — real CMP project:1718```19composeApp/20├── src/21│   ├── commonMain/          # Shared code — runs everywhere22│   │   └── kotlin/23│   │       ├── App.kt24│   │       ├── classes/     # Domain models25│   │       ├── dao/         # Room DAO (interface)26│   │       ├── di/          # Koin shared modules27│   │       ├── repository/  # Repository + ViewModel28│   │       ├── screens/     # Shared Compose UI29│   │       └── utils/       # AppColors, ThemeManager, TOTP30│   ├── androidMain/         # Android-specific31│   │   └── kotlin/32│   │       ├── MainActivity.kt33│   │       ├── dao/         # DatabaseFactory.android.kt34│   │       ├── di/          # Koin Android modules35│   │       └── utils/       # TOTP Android impl36│   ├── iosMain/             # iOS-specific37│   │   └── kotlin/38│   │       ├── MainViewController.kt39│   │       ├── dao/         # DatabaseFactory.ios.kt40│   │       ├── di/          # Koin iOS modules41│   │       └── utils/       # TOTP iOS impl42│   └── desktopMain/         # Desktop-specific43│       └── kotlin/44│           ├── main.kt45│           ├── dao/         # Desktop DB factory46│           └── utils/       # TOTP Desktop impl47```4849**Rule:** maximum code in `commonMain`. Only platform-specific APIs go in `androidMain`/`iosMain`/`desktopMain`.5051## expect/actual Pattern5253Declare API in `commonMain`, implement per platform:5455### Database Factory5657```kotlin58// commonMain — expect declaration59expect class DatabaseFactory {60    fun create(): RoomDatabase.Builder<AppDatabase>61}6263// androidMain — actual implementation64actual class DatabaseFactory(private val context: Context) {65    actual fun create(): RoomDatabase.Builder<AppDatabase> {66        val dbFile = context.getDatabasePath("auth.db")67        return Room.databaseBuilder(context, AppDatabase::class.java, dbFile.absolutePath)68    }69}7071// iosMain — actual implementation72actual class DatabaseFactory {73    actual fun create(): RoomDatabase.Builder<AppDatabase> {74        val dbFile = NSHomeDirectory() + "/Documents/auth.db"75        return Room.databaseBuilder(AppDatabase::class.java, dbFile)76    }77}7879// desktopMain — actual implementation80actual class DatabaseFactory {81    actual fun create(): RoomDatabase.Builder<AppDatabase> {82        val dbFile = File(System.getProperty("user.home"), ".auth/auth.db")83        return Room.databaseBuilder(AppDatabase::class.java, dbFile.absolutePath)84    }85}86```8788### TOTP Generator (Crypto differs per platform)8990```kotlin91// commonMain92expect class TOTPGenerator() {93    fun generateCode(secret: String, timeStep: Long = 30L): String94}9596// androidMain — uses javax.crypto97actual class TOTPGenerator actual constructor() {98    actual fun generateCode(secret: String, timeStep: Long): String {99        val key = SecretKeySpec(Base32.decode(secret), "HmacSHA1")100        val mac = Mac.getInstance("HmacSHA1")101        mac.init(key)102        val time = System.currentTimeMillis() / 1000 / timeStep103        val hash = mac.doFinal(time.toByteArray())104        return extractOtp(hash)105    }106}107108// iosMain — uses CommonCrypto109actual class TOTPGenerator actual constructor() {110    actual fun generateCode(secret: String, timeStep: Long): String {111        // CommonCrypto HMAC implementation112        // ...113    }114}115```116117### Platform Time118119```kotlin120// commonMain121expect fun getCurrentTimeSeconds(): Long122123// androidMain124actual fun getCurrentTimeSeconds(): Long = System.currentTimeMillis() / 1000125126// iosMain127actual fun getCurrentTimeSeconds(): Long =128    NSDate().timeIntervalSince1970.toLong()129130// desktopMain131actual fun getCurrentTimeSeconds(): Long = System.currentTimeMillis() / 1000132```133134## Shared ViewModel135136```kotlin137// commonMain — ViewModel works across platforms with lifecycle-viewmodel-compose138class AuthViewModel(private val repository: AuthRepository) : ViewModel() {139    private val _searchQuery = MutableStateFlow("")140    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()141142    val accounts: Flow<List<AuthAccount>> = combine(143        repository.getAllAccounts(),144        _searchQuery145    ) { accounts, query ->146        if (query.isBlank()) accounts147        else accounts.filter {148            it.serviceName.contains(query, ignoreCase = true)149        }150    }151152    fun addAccount(account: AuthAccount) {153        viewModelScope.launch {154            repository.insertAccount(account)155        }156    }157}158```159160```toml161# Dependency for shared ViewModel162lifecycle-viewmodel-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose", version = "2.9.0" }163```164165**CMP lifecycle note:** `collectAsStateWithLifecycle()` not available in `commonMain`. Use `collectAsState()` in shared code. On Android-specific composables, use the lifecycle-aware version.166167## Koin DI in KMP168169```kotlin170// commonMain — shared module171val sharedModule = module {172    single { AuthRepository(get()) }173    viewModel { AuthViewModel(get()) }174    single { ThemeManager() }175}176177// commonMain — expect platform module178expect fun platformModule(): Module179180// androidMain181actual fun platformModule(): Module = module {182    single<AuthAccountDao> {183        DatabaseFactory(get()).create()184            .fallbackToDestructiveMigration()185            .build()186            .authAccountDao()187    }188    single { TOTPGenerator() }189}190191// iosMain192actual fun platformModule(): Module = module {193    single<AuthAccountDao> {194        DatabaseFactory().create()195            .fallbackToDestructiveMigration()196            .build()197            .authAccountDao()198    }199    single { TOTPGenerator() }200}201202// Initialization — commonMain203fun initializeKoin() {204    startKoin {205        modules(sharedModule, platformModule())206    }207}208```209210## Shared Compose UI211212From Authenticator — entire UI in `commonMain`:213214```kotlin215// commonMain — works on Android, iOS, Desktop216@Composable217fun App() {218    MaterialTheme {219        AuthenticatorApp()220    }221}222223// Android entry point224class MainActivity : ComponentActivity() {225    override fun onCreate(savedInstanceState: Bundle?) {226        super.onCreate(savedInstanceState)227        setContent { App() }228    }229}230231// iOS entry point232fun MainViewController(): UIViewController =233    ComposeUIViewController { App() }234235// Desktop entry point236fun main() = application {237    Window(238        onCloseRequest = ::exitApplication,239        title = "Authenticator"240    ) { App() }241}242```243244### Platform-Specific UI When Needed245246```kotlin247// commonMain — expect composable248@Composable249expect fun PlatformStatusBar(isDark: Boolean)250251// androidMain252@Composable253actual fun PlatformStatusBar(isDark: Boolean) {254    val systemUiController = rememberSystemUiController()255    systemUiController.setStatusBarColor(256        color = Color.Transparent,257        darkIcons = !isDark258    )259}260261// iosMain262@Composable263actual fun PlatformStatusBar(isDark: Boolean) {264    // iOS handles this through UIKit appearance265}266267// desktopMain268@Composable269actual fun PlatformStatusBar(isDark: Boolean) {270    // No-op on desktop271}272```273274## Ktor for Networking in KMP275276```kotlin277// commonMain278class AuthApi(private val client: HttpClient) {279    suspend fun getAccounts(): List<AccountDto> {280        return client.get("accounts").body()281    }282283    suspend fun createAccount(dto: CreateAccountDto): AccountDto {284        return client.post("accounts") {285            contentType(ContentType.Application.Json)286            setBody(dto)287        }.body()288    }289}290291// commonMain — shared client config292fun createHttpClient(): HttpClient {293    return HttpClient {294        install(ContentNegotiation) {295            json(Json {296                ignoreUnknownKeys = true297                prettyPrint = false298            })299        }300        install(Logging) {301            level = LogLevel.BODY302        }303        defaultRequest {304            url("https://api.example.com/v1/")305        }306    }307}308```309310Platform engines:311312```kotlin313// androidMain314actual fun createPlatformHttpClient(): HttpClient = HttpClient(OkHttp)315316// iosMain317actual fun createPlatformHttpClient(): HttpClient = HttpClient(Darwin)318319// desktopMain320actual fun createPlatformHttpClient(): HttpClient = HttpClient(CIO)321```322323## Room vs SQLDelight for KMP324325| Aspect | Room (2.7+) | SQLDelight |326|--------|-------------|------------|327| **KMP support** | Android + JVM + iOS (limited) | Full KMP (all targets) |328| **API style** | Annotations + DAO interface | Raw SQL + generated Kotlin |329| **Type safety** | Compile-time via KSP | Compile-time via SQL verification |330| **Flow support** | Built-in `Flow<List<T>>` | `.asFlow().mapToList()` |331| **Migration** | Auto + manual | Numbered `.sqm` files |332| **Learning curve** | Easier for Android devs | Easier for SQL-first devs |333| **Maturity on KMP** | Newer (2024+) | Battle-tested |334335**Choose Room when:** team knows Room, targeting Android + iOS, using Koin/Hilt already.336**Choose SQLDelight when:** need all KMP targets, want SQL-first approach, complex queries.337338From Authenticator — Room in KMP:339340```kotlin341// commonMain342@Database(entities = [AuthAccountEntity::class], version = 1)343@ConstructedBy(AppDatabaseConstructor::class)344abstract class AppDatabase : RoomDatabase() {345    abstract fun authAccountDao(): AuthAccountDao346}347348@Suppress("NO_ACTUAL_FOR_EXPECT")349expect object AppDatabaseConstructor : RoomDatabaseConstructor<AppDatabase>350```351352## Anti-Patterns353354- **Platform-specific code in commonMain** → won't compile on other targets. Use expect/actual355- **`Context` in shared ViewModel** → Android-only. Inject platform abstractions via DI356- **`collectAsStateWithLifecycle` in commonMain** → not available. Use `collectAsState` in shared code357- **Hardcoded file paths** → each platform has different file system. Use expect/actual for paths358- **Skipping `iosMain` implementations** → will crash on iOS launch. Always implement all expect declarations359- **Single platform Engine for Ktor** → use expect/actual to pick OkHttp/Darwin/CIO per platform360

Search chapters, reference and source filenames.