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/
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")
}
Expect/Actual Pattern
Bridge platform differences:
// commonMain
expect fun getPlatformName(): String
// androidMain
actual fun getPlatformName(): String = "Android"
// iosMain
actual fun getPlatformName(): String = "iOS"
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()
}
}
}
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")
}
8 production-ready Android app templates on Gumroad.
Browse templates → Gumroad
Top comments (0)