KMP for Mobile Developers @ Droidcon Berlin 2021
KMP for MobileDevelopersEnrique López Mañas
View Slide
Ego Slide• Google Developer Expert•🇻🇳 🇩🇪 🇪🇸• Kotlin Weekly publisher• @eenriquelopez• Mainly Android Kotlin, Backend Kotlin, iOS (mostly Swift)
expect fun
Motivation< CostsSharing code within the companyFeature teams> QualityOne tech-stack
Multiplatform developmentPlatform ProprietaryHybrid HTML &JavaScript FrameworksCross-platformNative
KotlinModern language
Kotlin
KotlinInterop
KotlinCommunity support
KotlinTop-notch tooling
KotlinSharing is optional!No life or death commitment
Kotlin/AnywhereAndroidBrowserServer
Kotlin/NativeCommonJVM NativeiOSframeworkYour iOSdevYourAndroidDevJS
Kotlin/Native or KMP or KMM
KMPSharing architecture (not UI)Shared UI is a mess
Kotlin/Native- Uses LLVM (5.0)- Provides runtime guarantees- Exceptions, memory management- Interop with C/Objective-C (Swift)- Platform libraries (POSIX, Apple Frameworks, Win32, DOM, etc)
Kotlin/NativeKotlinCompilerLLVMKotlin SourceCode (.kt)PlatformBinaryIR
The compiler-Shares Front-end with Kotlin/JVM and Kotlin/JS- Written in Java and Kotlin- Produces bitcode via LLVM API
Memory Management- ARC with Cycle Collector- When working pure Kotlin,don’t worry about memory management- Weak references supported- Memory sharing model- Different threads have disjoint object graphs- Object subgraphs can be transferred between threads- Immutable objects can be shared
Interoperatibility- Interoperatibility with C, Objective-C and Swift- Kotlin can call C/Objective-C and vice-versa- Kotlin can extend Objective-C classes and vice-versa- Memory management aware of Objective-C runtime
Mapping- Numbers are kept- Strings converted- Kotlin declarations wrapping C entities (functions, struct, unions, etc.) are auto-generated- Objective-C OO concepts (classes, protocols, blocks) are represented asmatching Kotlin entities (classes, interfaces, lambdas)- For Objective-C, Kotlin code can be compiled to a framework
Mapping
Kotlin Library- Hold collection of code for reusability and sharing- Own format: ‘klib’ extension, which holds metadata and bitcode- Tool for creating and storing libraries in repositories
expect/actual
expect/actual JVM
expect/actual JS
expect/actual// Commonexpect fun randomUUID(): String// Androidimport java.util.*actual fun randomUUID() = UUID.randomUUID().toString() // iOSimport platform.Foundation.NSUUIDactual fun randomUUID(): String = NSUUID().UUIDString()
SquareJetBrainsTouchLab Others
Community projects- Sqldelight- SQLiter- Multiplatform settings- Stately- OKIO2
Existing native libraries- Ktor- Kotlinx.Coroutines- Kotlinx.io- Atomic-fu
ktor- Web application framework -Domain Specific Language (DSL) syntax for web apps-Kotlin coroutines forasynchronous programming -Can be used on web, iOS and Android -Provides a unified toolset with a single language, like Node.js but with type-safetyand build-concurrency.
ktor
CoroutinesJetBrains async library
Coroutines
kotlinx.ioLibrary for I/O primitives building and manipulationsExperimental
kotlinx.io
AtomicFULibrary for atomic operations in Kotlin
Considerations in stateNo threading primitives: synchronized, volatileUse atomic-fu instead
AtomicFU
SQLiter•Evoution of knarch.db •From Touchlab •SQLiter -> SQL Driver
SQLiter.DatabaseInstance.
SQLiter
Multiplatform settingsSharedPreferences on Android and NSUserDefaults on iOS.
Multiplatform settings
kotlinx.serialization
Considerations in stateAn object belongs to one thread
Considerations in stateFrozen objects can be shared by threads
Concurrency - frozen objectsEverything you have written until now is not frozen
Considerations in stateRuntime safety: KMP can verify safe mutability
Considerations in state - Generics
Considerations in state
Considerations in stateExhaustive enums
Considerations in stateDefault arguments
Considerations in state// Kotlinenum class LogLevel {ERROR,WARNING,INFO,DEBUG}class Logger {companion object default {fun log(level: LogLevel = LogLevel.ERROR, message: String, completion: (Boolean) ->Unit) { }}}
Considerations in state// SwiftLogger.default.log(.error, "An error ocurred") {// Closure}
Considerations in stateiOS devs?
Architecturehttps://proandroiddev.com/kotlin-multiplatform-mvvm-clean-architecture-f20b99f90b95Javier Arroyo
KMM Survey Q1-Q2 2021
Case studies?https://kotlinlang.org/lp/mobile/case-studies/
The futureHard to make predictions, easier to bet safe“I don’t know what will happen in 10 years, but there willbe people asking in SO about regular expressions, andthere will be another JS framework ”
The future@lehtimaeki
Recommendations- Use it with caution- Shared components- Keep versioning in mind- Do not compromise 100% of a project
Further resourcesKotlin Slack (kotlinlang.slack.com)Touchlab resources (https://github.com/touchlab)Kotlin Weekly (http://kotlinweekly.net)K/N documentation (https://kotlinlang.org/docs/native-overview.html)
Thanks!