Share
Embed
Best Practices for Developing Amazing Kotlin Multiplatform Apps
Appdevcon edition
pahill
March 14, 2024
Transcript
98 slides
-
Kotlin Multiplatform Apps Pamela Hill Developer Advocate - JetBrains Best
Practices for Developing ✨Amazing✨ -
• It’s not an introduction to Kotlin Multiplatform (that was
Marco’s talk). • It’s not about all the best practices of the technology. • It’s not about processes and tooling. What this talk is not about -
Three sets of best practices to address some common questions
and mistakes. 1. Question: How do I make my Kotlin/Swift interop look more like idiomatic Swift? 2. Question: Can I / how do I consume suspend functions and Flows from Swift? 3. Mistake: Misusing expect/actual building blocks. What this talk is about -
• Decision made in ~2018 for Kotlin to be interoperable
with Objective-C, not Swift • Why? ◦ Can be used in all iOS projects, not just Swift ones ◦ Swift was still on the road to maturity/adoption at that stage Kotlin/Objective-C interop -
This means: Kotlin is not directly interoperable with Swift, but
indirectly via an Objective-C bridge. -
Some Kotlin features: • Work exactly as expected • Work
with a small workaround • Work better with a community solution • Don’t work (small minority) What this means for Swift developers -
JetBrains is working on Swift export, which will solve the
Kotlin-to-Swift interop challenges. -
The community is also helping improve the current experience with
plugins and libraries. 🤝 -
• Interoperability encyclopedia • Explains how Kotlin features currently work
from Swift • Lots of code samples • Gives workarounds / community solutions • Includes playground app with runnable samples Kotlin/Swift Interopedia [kotl.in/interopedia] -
✅ Some features work exactly as expected ✏ Some features
need a slight modification 🤝 Some features need a community solution 🛑 Some features don’t work -
• Classes • Properties • Functions & constructors • Higher-order
functions • Some basic types • Some collections • Etc. Examples -
✅ Some features work exactly as expected ✏ Some features
need a slight modification 🤝 Some features need a community solution 🛑 Some features don’t work -
• Basic types like integers and Char • Collections with
basic types • Objects • Companion objects • Some generics • Etc. Examples -
object AnalyticsLogger { const val LOGIN_SCREEN_NAME = "login_screen" fun logLogin()
{ println(LOGIN_SCREEN_NAME) } } Slight modification example - Objects ✓ Property called ‘shared’ appears Used from Kotlin: AnalyticsLogger.LOGIN_SCREEN_NAME AnalyticsLogger.logLogin() Used from Swift: -
✅ Some features work exactly as expected ✏ Some features
need a slight modification 🤝 Some features need a community solution 🛑 Some features don’t work -
Some community rock stars 🎸 @TouchlabHQ • Created SKIE @RickClephas
• Created KMP-NativeCoroutines • Contributed several Swift interop annotations -
• Kotlin compiler plugin • Narrows gap between Kotlin and
Swift • Stepping stone to official Swift interop • List of features always growing, but for now: ◦ Enumerations (enums, sealed hierarchies) ◦ Functions (default arguments etc) ◦ Reactive (coroutines and Flows) [next section] SKIE [https://skie.touchlab.co/] -
plugins { … id("co.touchlab.skie") version ("0.6.1") } Installing the SKIE
plugin build.gradle.kts -
func colorAbbreviations(colors: Colors) -> String { switch colors { case
.red: return "R" case .green: return "G" case .blue: return "B" default: return "D" } } Enum Interop - from Swift Somewhere in Swift -
func colorAbbreviations(colors: Colors) -> String { switch colors { case
.red: return "R" case .green: return "G" case .blue: return "B" default: return "D" } } Enum Interop - from Swift Somewhere in Swift Required: Switch must be exhaustive -
__attribute__((swift_name("Colors"))) @interface ComposeAppColors : ComposeAppKotlinEnum<ComposeAppColors *> @property (class, readonly) ComposeAppColors
*red __attribute__((swift_name("red"))); @property (class, readonly) ComposeAppColors *green __attribute__((swift_name("green"))); @property (class, readonly) ComposeAppColors *blue __attribute__((swift_name("blue"))); + (ComposeAppKotlinArray<ComposeAppColors *> *)values __attribute__((swift_name("values()"))); @property (class, readonly) NSArray<ComposeAppColors *> *entries __attribute__((swift_name("entries"))); @end Enum Interop - The Investigation Somewhere in Objective-C -
public enum Colors : Swift.Hashable, Swift.CaseIterable, Swift._ObjectiveCBridgeable { case red
case green case blue … } SKIE Enum Interop - The Investigation -
public enum Colors : Swift.Hashable, Swift.CaseIterable, Swift._ObjectiveCBridgeable { case red
case green case blue … } SKIE Enum Interop - The Investigation -
func colorAbbreviations(colors: Colors) -> String { switch colors { case
.red: return "R" case .green: return "G" case .blue: return "B" } } SKIE Enum interop Somewhere in Swift No default case needed! -
sealed class NetworkResponse { data class Data(val body: String) :
NetworkResponse() data object Error : NetworkResponse() } Sealed Classes Interop Somewhere in Kotlin -
func processNetworkResponse(response: NetworkResponse){ switch response { case is NetworkResponse.Data: print("Data
\(body)"); case is NetworkResponse.Error: print("Error"); default: print("Default") } } Sealed Classes Interop - from Swift Somewhere in Swift -
func processNetworkResponse(response: NetworkResponse){ switch response { case is NetworkResponse.Data: print("Data
\(body)"); case is NetworkResponse.Error: print("Error"); default: print("Default") } } Sealed Classes Interop - from Swift Somewhere in Swift Required: Switch must be exhaustive -
__attribute__((swift_name("NetworkResponse"))) @interface ComposeAppNetworkResponse : ComposeAppBase @end __attribute__((swift_name("NetworkResponse.Data"))) @interface ComposeAppNetworkResponseData :
ComposeAppNetworkResponse … @property (readonly) NSString *body __attribute__((swift_name("body"))); @end __attribute__((swift_name("NetworkResponse.Error"))) @interface ComposeAppNetworkResponseError : ComposeAppNetworkResponse … @end Sealed Classes Interop - The Investigation Somewhere in Objective-C -
__attribute__((swift_name("NetworkResponse"))) @interface ComposeAppNetworkResponse : ComposeAppBase @end __attribute__((swift_name("NetworkResponse.Data"))) @interface ComposeAppNetworkResponseData :
ComposeAppNetworkResponse … @property (readonly) NSString *body __attribute__((swift_name("body"))); @end __attribute__((swift_name("NetworkResponse.Error"))) @interface ComposeAppNetworkResponseError : ComposeAppNetworkResponse … @end Sealed Classes Interop - The Investigation Somewhere in Objective-C -
__attribute__((swift_name("NetworkResponse"))) @interface ComposeAppNetworkResponse : ComposeAppBase @end __attribute__((swift_name("NetworkResponse.Data"))) @interface ComposeAppNetworkResponseData :
ComposeAppNetworkResponse … @property (readonly) NSString *body __attribute__((swift_name("body"))); @end __attribute__((swift_name("NetworkResponse.Error"))) @interface ComposeAppNetworkResponseError : ComposeAppNetworkResponse … @end Sealed Classes Interop - The Investigation Somewhere in Objective-C -
public extension ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse { @frozen enum __Sealed : Swift.Hashable {
case data(ComposeApp.NetworkResponse.Data) case error(ComposeApp.NetworkResponse.Error) } } SKIE Sealed Classes Interop - The Investigation Somewhere in Swift -
public func onEnum<__Sealed : ComposeApp.NetworkResponse>(of sealed: __Sealed) -> ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed {
if let sealed = sealed as? ComposeApp.NetworkResponse.Data { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.data(seal ed) } else if let sealed = sealed as? ComposeApp.NetworkResponse.Error { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.error(sea led) } else { fatalError("Unknown subtype. This error should not happen under normal circumstances since SirClass: ComposeApp.NetworkResponse is sealed.") } } SKIE Sealed Classes Interop - The Investigation Somewhere in Swift -
public func onEnum<__Sealed : ComposeApp.NetworkResponse>(of sealed: __Sealed) -> ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed {
if let sealed = sealed as? ComposeApp.NetworkResponse.Data { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.data(seal ed) } else if let sealed = sealed as? ComposeApp.NetworkResponse.Error { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.error(sea led) } else { fatalError("Unknown subtype. This error should not happen under normal circumstances since SirClass: ComposeApp.NetworkResponse is sealed.") } } SKIE Sealed Classes Interop - The Investigation Somewhere in Swift -
public func onEnum<__Sealed : ComposeApp.NetworkResponse>(of sealed: __Sealed) -> ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed {
if let sealed = sealed as? ComposeApp.NetworkResponse.Data { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.data(seal ed) } else if let sealed = sealed as? ComposeApp.NetworkResponse.Error { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.error(sea led) } else { fatalError("Unknown subtype. This error should not happen under normal circumstances since SirClass: ComposeApp.NetworkResponse is sealed.") } } SKIE Sealed Classes Interop - The Investigation Somewhere in Swift -
public func onEnum<__Sealed : ComposeApp.NetworkResponse>(of sealed: __Sealed) -> ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed {
if let sealed = sealed as? ComposeApp.NetworkResponse.Data { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.data(seal ed) } else if let sealed = sealed as? ComposeApp.NetworkResponse.Error { return ComposeApp.Skie.KotlinProject__composeApp.NetworkResponse.__Sealed.error(sea led) } else { fatalError("Unknown subtype. This error should not happen under normal circumstances since SirClass: ComposeApp.NetworkResponse is sealed.") } } SKIE Sealed Classes Interop - The Investigation Somewhere in Swift -
func processNetworkResponse(response: NetworkResponse){ switch onEnum(of: response) { case .data: print("Data
\(body)"); case .error: print("Error"); } } SKIE Sealed Classes interop Somewhere in Swift No default case needed! -
fun connect(retries: Int = 2) { … } Default Args
Interop Somewhere in Kotlin -
connect() Default Args Interop - from Swift Somewhere in Swift
Missing argument for parameter ‘retries’ in call -
@DefaultArgumentInterop.Enabled fun connect(retries: Int = 2) { … } SKIE
Default Args Interop - The Investigation Somewhere in Kotlin -
public func connect() { return ComposeApp.PlatformKt.connect() } public func connect(retries:
Swift.Int32) { return ComposeApp.PlatformKt.connect(retries: retries) } SKIE Default Args Interop - The Investigation Somewhere in Swift -
✅ Some features work exactly as expected ✏ Some features
need a slight modification 🤝 Some features need a community solution 🛑 Some features don’t work -
Android with Compose Use LaunchedEffect var rocketLaunches by remember {
mutableStateOf(emptyList<RocketLaunch>()) } LaunchedEffect(Unit) { rocketLaunches = sdk.getLaunches() } PullToRefreshRocketLaunches( … listRocketLaunch = rocketLaunches, … ) -
Android with Compose Use LaunchedEffect var rocketLaunches by remember {
mutableStateOf(emptyList<RocketLaunch>()) } LaunchedEffect(Unit) { rocketLaunches = sdk.getLaunches() } PullToRefreshRocketLaunches( … listRocketLaunch = rocketLaunches, … ) -
Android with Compose Use LaunchedEffect var rocketLaunches by remember {
mutableStateOf(emptyList<RocketLaunch>()) } LaunchedEffect(Unit) { rocketLaunches = sdk.getLaunches() } PullToRefreshRocketLaunches( … listRocketLaunch = rocketLaunches, … ) -
iOS with SwiftUI Approach 1: Completion Handlers sdk.getLaunches(completionHandler: { launches,
error in if let launches = launches { self.launches = .result(launches) } else { self.launches = .error(error?.localizedDescription ?? "error") } }) -
iOS with SwiftUI Approach 1: Completion Handlers sdk.getLaunches(completionHandler: { launches,
error in if let launches = launches { self.launches = .result(launches) } else { self.launches = .error(error?.localizedDescription ?? "error") } }) -
iOS with SwiftUI Approach 2: async/await @MainActor class ViewModel: ObservableObject
{ … Task { do { let launches = try await sdk.getLaunches() self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } } -
iOS with SwiftUI Approach 2: async/await @MainActor class ViewModel: ObservableObject
{ … Task { do { let launches = try await sdk.getLaunches() self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } } -
iOS with SwiftUI Approach 2: async/await @MainActor class ViewModel: ObservableObject
{ … Task { do { let launches = try await sdk.getLaunches() self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } } -
iOS with SwiftUI Approach 2: async/await @MainActor class ViewModel: ObservableObject
{ … Task { do { let launches = try await sdk.getLaunches() self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } } -
iOS with SwiftUI Approach 3: KMP-NativeCoroutines class SpaceXSDK () {
private val api = SpaceXApi() @NativeCoroutines @Throws(Exception::class) suspend fun getLaunches(): List<RocketLaunch> { return api.getAllLaunches() } } -
iOS with SwiftUI Approach 3: KMP-NativeCoroutines @MainActor class ViewModel: ObservableObject
{ … let task = Task { do { let launches = try await asyncFunction(for: sdk.getLaunches()) self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } task.cancel() } } -
iOS with SwiftUI Approach 3: KMP-NativeCoroutines @MainActor class ViewModel: ObservableObject
{ … let task = Task { do { let launches = try await asyncFunction(for: sdk.getLaunches()) self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } task.cancel() } } -
iOS with SwiftUI Approach 4: SKIE class SpaceXSDK () {
private val api = SpaceXApi() @Throws(Exception::class) suspend fun getLaunches(): List<RocketLaunch> { return api.getAllLaunches() } } -
iOS with SwiftUI Approach 4: SKIE @MainActor class ViewModel: ObservableObject
{ … let task = Task { do { let launches = try await sdk.getLaunches() self.launches = .result(launches) } catch { self.launches = .error(error.localizedDescription) } } task.cancel() } } -
The problem with Flows on iOS • Objective-C does not
support generics on protocols • So, flow interfaces lose their generic value type • Still need cancellation support and main thread safety -
iOS with SwiftUI Solution 1: KMP-NativeCoroutines @MainActor class ViewModel: ObservableObject
{ @Published var launches = LoadableLaunches.loading … func startObserving(){ self.launches = .loading Task { do { let sequence = asyncSequence(for: self.sdk.getLaunches()) for try await data in sequence { self.launches = .result(data) } } catch { print("Failed with error: \(error)") self.launches = .error("Error") } } -
iOS with SwiftUI Solution 1: KMP-NativeCoroutines @MainActor class ViewModel: ObservableObject
{ @Published var launches = LoadableLaunches.loading … func startObserving(){ self.launches = .loading Task { do { let sequence = asyncSequence(for: self.sdk.getLaunches()) for try await data in sequence { self.launches = .result(data) } } catch { print("Failed with error: \(error)") self.launches = .error("Error") } } -
class ViewModel: ObservableObject { @Published var launches = LoadableLaunches.loading …
func startObserving(){ self.launches = .loading Task { let sequence = self.sdk.getLaunches() for await data in sequence { self.launches = .result(data) } } } } iOS with SwiftUI Solution 2: SKIE Becomes Swift AsyncSequence Doesn’t need @MainActor annotation -
KMP-NativeCoroutines • Generates needed wrappers • Requires annotation, function wrappers
• Supports async/await, Combine, and RxSwift • Available for longer than SKIE, and may encounter fewer edge-cases -
SKIE • Augments the Objective-C API produced by the Kotlin
compiler • Requires no additional work after setup • Supports async/await, while Combine, RxSwift require adapters • Offers other features to produce a Swift-friendly API from Kotlin -
iosMain Kotlin/Native androidMain Kotlin/JVM commonMain Common Kotlin import java.util.* actual
fun randomUUID() = UUID.randomUUID().toString() import platform.Foundation.NSUUID actual fun randomUUID(): String = NSUUID().UUIDString() expect fun randomUUID(): String Expect/actual functions -
class AndroidPlatform: Platform class iOSPlatform: Platform interface Platform { val
name: String } Interfaces iosMain Kotlin/Native androidMain Kotlin/JVM commonMain Common Kotlin -
class AndroidPlatform: Platform … actual fun getPlatform() = AndroidPlatform() class
iOSPlatform: Platform … actual fun getPlatform() = iOSPlatform() interface Platform { val name: String } expect fun getPlatform(): Platform iosMain Kotlin/Native androidMain Kotlin/JVM commonMain Common Kotlin Factory functions -
class AndroidPlatform: Platform … class MyApp : Application() { override
fun onCreate() { super.onCreate() app(AndroidPlatform()) } } class iOSPlatform: Platform … @main struct iOSApp : App { init() { app(IOSPlatform()) } } interface Platform { val name: String } fun app(p: Platform) { // app logic } Early Entry Points iosMain Kotlin/Native androidMain Kotlin/JVM commonMain Common Kotlin -
class AndroidPlatform: Platform … actual val platformModule: Module = module
{ single<Platform> { AndroidPlatform() } } class iOSPlatform: Platform … actual val platformModule = module { single<Platform> { IOSPlatform() } } interface Platform { val name: String } expect val platformModule: Module iosMain Kotlin/Native androidMain Kotlin/JVM commonMain Common Kotlin Dependency Injection with Koin