DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Kotlin Multiplatform + Compose Multiplatform Getting Started

Build shared code for Android, iOS, and web with Kotlin Multiplatform and Compose.

KMP Project Structure

Organize your project for code sharing:

myapp/
├── shared/
│   ├── src/commonMain/kotlin/  # Shared code
│   ├── src/androidMain/kotlin/
│   └── src/iosMain/kotlin/
├── android/
│   └── src/main/java/
└── ios/
    └── MyApp.xcodeproj/
Enter fullscreen mode Exit fullscreen mode

Common Main Setup

Define platform-independent business logic:

// shared/src/commonMain/kotlin/App.kt
@Composable
fun App() {
    MaterialTheme {
        Surface {
            Text("Hello Multiplatform!")
        }
    }
}

// shared/src/commonMain/kotlin/ViewModel.kt
class AppViewModel : ViewModel() {
    val state = MutableStateFlow("Initial")
}
Enter fullscreen mode Exit fullscreen mode

Expect/Actual Pattern

Bridge platform differences:

// commonMain
expect fun getPlatformName(): String

// androidMain
actual fun getPlatformName(): String = "Android"

// iosMain
actual fun getPlatformName(): String = "iOS"
Enter fullscreen mode Exit fullscreen mode

Shared ViewModel with StateFlow

Share state across platforms:

@HiltViewModel
class UserViewModel : ViewModel() {
    private val _users = MutableStateFlow<List<User>>(emptyList())
    val users: StateFlow<List<User>> = _users.asStateFlow()

    fun fetchUsers() {
        viewModelScope.launch {
            _users.value = userRepository.getUsers()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Ktor Client for Shared HTTP

Make API calls from shared code:

val client = HttpClient {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}

suspend fun fetchUsers(): List<User> {
    return client.get("https://api.example.com/users")
}
Enter fullscreen mode Exit fullscreen mode

8 production-ready Android app templates on Gumroad.
Browse templatesGumroad

Top comments (0)