Kotlin Multiplatform — Shared Business Logic for Mobile

## Overview

25 stars

Best use case

Kotlin Multiplatform — Shared Business Logic for Mobile is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

## Overview

Teams using Kotlin Multiplatform — Shared Business Logic for Mobile should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/kotlin-multiplatform/SKILL.md --create-dirs "https://raw.githubusercontent.com/ComeOnOliver/skillshub/main/skills/TerminalSkills/skills/kotlin-multiplatform/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/kotlin-multiplatform/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How Kotlin Multiplatform — Shared Business Logic for Mobile Compares

Feature / AgentKotlin Multiplatform — Shared Business Logic for MobileStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

## Overview

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Kotlin Multiplatform — Shared Business Logic for Mobile


## Overview


Kotlin Multiplatform (KMP), JetBrains' technology for sharing code between Android, iOS, web, and desktop applications. Helps developers build shared business logic, networking, and data layers in Kotlin while keeping UI native on each platform.


## Instructions

### Project Structure

```
my-kmp-app/
├── shared/                              # Shared Kotlin code
│   └── src/
│       ├── commonMain/                  # Platform-independent code
│       │   └── kotlin/com/example/
│       │       ├── data/                # Repositories, models
│       │       ├── domain/              # Use cases, business logic
│       │       └── network/             # API clients
│       ├── androidMain/                 # Android-specific implementations
│       │   └── kotlin/com/example/
│       │       └── platform/
│       └── iosMain/                     # iOS-specific implementations
│           └── kotlin/com/example/
│               └── platform/
├── androidApp/                          # Android app (Jetpack Compose)
├── iosApp/                              # iOS app (SwiftUI)
└── build.gradle.kts
```

### Shared Business Logic

```kotlin
// shared/src/commonMain/kotlin/com/example/domain/TaskRepository.kt
// This code runs on BOTH Android and iOS — write once, test once.

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class TaskRepository(
    private val api: TaskApi,
    private val db: TaskDatabase,
) {
    /**
     * Get all tasks, fetching from API and caching in local DB.
     * Returns a Flow that emits updates when data changes.
     */
    fun getTasks(): Flow<List<Task>> {
        return db.observeAll().map { entities ->
            entities.map { it.toTask() }
        }
    }

    /**
     * Sync tasks from the remote API to the local database.
     * Called on app launch and pull-to-refresh.
     */
    suspend fun syncTasks() {
        val remoteTasks = api.fetchTasks()
        db.upsertAll(remoteTasks.map { it.toEntity() })
    }

    /**
     * Create a new task — saves locally and syncs to server.
     * If offline, saves locally and syncs when connection returns.
     */
    suspend fun createTask(title: String, priority: Priority): Task {
        val task = Task(
            id = generateUuid(),
            title = title,
            priority = priority,
            status = TaskStatus.TODO,
            createdAt = Clock.System.now(),
        )
        db.insert(task.toEntity())

        try {
            api.createTask(task.toRequest())
        } catch (e: Exception) {
            // Queue for sync when online
            db.markPendingSync(task.id)
        }

        return task
    }

    suspend fun updateStatus(taskId: String, status: TaskStatus) {
        db.updateStatus(taskId, status)
        try {
            api.updateTask(taskId, UpdateTaskRequest(status = status))
        } catch (e: Exception) {
            db.markPendingSync(taskId)
        }
    }
}
```

### Networking with Ktor

```kotlin
// shared/src/commonMain/kotlin/com/example/network/TaskApi.kt
// Ktor is Kotlin's multiplatform HTTP client — same code on Android/iOS.

import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json

class TaskApi(private val baseUrl: String, private val authToken: String) {
    private val client = HttpClient {
        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true    // Don't crash on extra API fields
                isLenient = true
            })
        }
        defaultRequest {
            header("Authorization", "Bearer $authToken")
        }
    }

    suspend fun fetchTasks(): List<TaskResponse> {
        return client.get("$baseUrl/api/tasks").body()
    }

    suspend fun createTask(request: CreateTaskRequest): TaskResponse {
        return client.post("$baseUrl/api/tasks") {
            setBody(request)
        }.body()
    }

    suspend fun updateTask(id: String, request: UpdateTaskRequest): TaskResponse {
        return client.patch("$baseUrl/api/tasks/$id") {
            setBody(request)
        }.body()
    }
}
```

### Platform-Specific Code with expect/actual

```kotlin
// shared/src/commonMain/kotlin/com/example/platform/Platform.kt
// 'expect' declares what each platform must implement.

expect fun generateUuid(): String
expect fun getPlatformName(): String

// shared/src/androidMain/kotlin/com/example/platform/Platform.kt
actual fun generateUuid(): String = java.util.UUID.randomUUID().toString()
actual fun getPlatformName(): String = "Android ${android.os.Build.VERSION.SDK_INT}"

// shared/src/iosMain/kotlin/com/example/platform/Platform.kt
import platform.Foundation.NSUUID
import platform.UIKit.UIDevice

actual fun generateUuid(): String = NSUUID().UUIDString()
actual fun getPlatformName(): String = UIDevice.currentDevice.systemName() +
    " " + UIDevice.currentDevice.systemVersion
```

### Local Database with SQLDelight

```kotlin
// shared/src/commonMain/sqldelight/com/example/db/Task.sq
// SQLDelight generates type-safe Kotlin from SQL — works on all platforms.

CREATE TABLE TaskEntity (
    id TEXT NOT NULL PRIMARY KEY,
    title TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'todo',
    priority TEXT NOT NULL DEFAULT 'medium',
    pending_sync INTEGER NOT NULL DEFAULT 0,
    created_at INTEGER NOT NULL
);

selectAll:
SELECT * FROM TaskEntity ORDER BY created_at DESC;

insert:
INSERT OR REPLACE INTO TaskEntity(id, title, status, priority, created_at)
VALUES (?, ?, ?, ?, ?);

updateStatus:
UPDATE TaskEntity SET status = ? WHERE id = ?;

markPendingSync:
UPDATE TaskEntity SET pending_sync = 1 WHERE id = ?;

getPendingSync:
SELECT * FROM TaskEntity WHERE pending_sync = 1;
```

### ViewModel (Shared UI Logic)

```kotlin
// shared/src/commonMain/kotlin/com/example/viewmodel/TaskListViewModel.kt
// Shared ViewModel — both Android and iOS consume this.

import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class TaskListViewModel(private val repository: TaskRepository) {
    private val _uiState = MutableStateFlow(TaskListUiState())
    val uiState: StateFlow<TaskListUiState> = _uiState.asStateFlow()

    init {
        // Observe local database changes
        repository.getTasks()
            .onEach { tasks ->
                _uiState.update { it.copy(tasks = tasks, isLoading = false) }
            }
            .launchIn(viewModelScope)

        // Initial sync from server
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            try {
                repository.syncTasks()
            } catch (e: Exception) {
                _uiState.update { it.copy(error = e.message) }
            }
            _uiState.update { it.copy(isLoading = false) }
        }
    }

    fun createTask(title: String, priority: Priority) {
        viewModelScope.launch {
            repository.createTask(title, priority)
        }
    }
}

data class TaskListUiState(
    val tasks: List<Task> = emptyList(),
    val isLoading: Boolean = true,
    val error: String? = null,
)
```

## Installation

```kotlin
// build.gradle.kts (shared module)
plugins {
    kotlin("multiplatform")
    kotlin("plugin.serialization")
    id("app.cash.sqldelight")
}

kotlin {
    androidTarget()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    sourceSets {
        commonMain.dependencies {
            implementation("io.ktor:ktor-client-core:2.3.7")
            implementation("io.ktor:ktor-client-content-negotiation:2.3.7")
            implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7")
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
            implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.5.0")
            implementation("app.cash.sqldelight:coroutines-extensions:2.0.1")
        }
        androidMain.dependencies {
            implementation("io.ktor:ktor-client-okhttp:2.3.7")
            implementation("app.cash.sqldelight:android-driver:2.0.1")
        }
        iosMain.dependencies {
            implementation("io.ktor:ktor-client-darwin:2.3.7")
            implementation("app.cash.sqldelight:native-driver:2.0.1")
        }
    }
}
```


## Examples


### Example 1: Setting up Kotlin Multiplatform with a custom configuration

**User request:**

```
I just installed Kotlin Multiplatform. Help me configure it for my TypeScript + React workflow with my preferred keybindings.
```

The agent creates the configuration file with TypeScript-aware settings, configures relevant plugins/extensions for React development, sets up keyboard shortcuts matching the user's preferences, and verifies the setup works correctly.

### Example 2: Extending Kotlin Multiplatform with custom functionality

**User request:**

```
I want to add a custom shared business logic to Kotlin Multiplatform. How do I build one?
```

The agent scaffolds the extension/plugin project, implements the core functionality following Kotlin Multiplatform's API patterns, adds configuration options, and provides testing instructions to verify it works end-to-end.


## Guidelines

1. **Share logic, not UI** — Share business logic, networking, data layer in Kotlin; keep UI native (Jetpack Compose on Android, SwiftUI on iOS)
2. **expect/actual for platform APIs** — Use expect/actual for platform-specific code (file system, biometrics, notifications)
3. **Ktor for HTTP** — Ktor is the standard multiplatform HTTP client; it uses OkHttp on Android and URLSession on iOS under the hood
4. **SQLDelight for local DB** — SQLDelight generates type-safe Kotlin from SQL; works on all platforms with platform-specific drivers
5. **Kotlin Serialization** — Use `@Serializable` data classes; works across all platforms unlike Gson or Moshi
6. **Coroutines + Flow** — Use Kotlin Coroutines for async work and Flow for reactive streams; both are fully multiplatform
7. **Start with shared module** — Build the shared module with tests first; then wrap with platform UIs
8. **Compose Multiplatform for UI** — If you want shared UI too, use Compose Multiplatform (covers Android, iOS, desktop, web)

Related Skills

retry-logic-helper

25
from ComeOnOliver/skillshub

Retry Logic Helper - Auto-activating skill for API Integration. Triggers on: retry logic helper, retry logic helper Part of the API Integration skill category.

automating-mobile-app-testing

25
from ComeOnOliver/skillshub

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

recipe-create-shared-drive

25
from ComeOnOliver/skillshub

Create a Google Shared Drive and add members with appropriate roles.

gws-shared

25
from ComeOnOliver/skillshub

gws CLI: Shared patterns for authentication, global flags, and output formatting.

kotlin-springboot

25
from ComeOnOliver/skillshub

Get best practices for developing applications with Spring Boot and Kotlin.

kotlin-mcp-server-generator

25
from ComeOnOliver/skillshub

Generate a complete Kotlin MCP server project with proper structure, dependencies, and implementation using the official io.modelcontextprotocol:kotlin-sdk library.

create-spring-boot-kotlin-project

25
from ComeOnOliver/skillshub

Create Spring Boot Kotlin Project Skeleton

apollo-kotlin

25
from ComeOnOliver/skillshub

Guide for building applications with Apollo Kotlin, the GraphQL client library for Android and Kotlin. Use this skill when: (1) setting up Apollo Kotlin in a Gradle project for Android, Kotlin/JVM, or KMP, (2) configuring schema download and codegen for GraphQL services, (3) configuring an `ApolloClient` with auth, interceptors, and caching, (4) writing queries, mutations, or subscriptions,

../../../business-growth/revenue-operations/SKILL.md

25
from ComeOnOliver/skillshub

No description provided.

../../../business-growth/customer-success-manager/SKILL.md

25
from ComeOnOliver/skillshub

No description provided.

../../../agents/business-growth/cs-growth-strategist.md

25
from ComeOnOliver/skillshub

No description provided.

../../../business-growth/contract-and-proposal-writer/SKILL.md

25
from ComeOnOliver/skillshub

No description provided.