Building a Kotlin Multiplatform Library for Android and iOS: A Starter Guide
As I embark on a new side project, I've decided to explore (KMM) to create a shared library that will house all business logic. Inspired by the BLoC architecture pattern. The cherry on top? Each platform will still boast native UIs to ensure top-notch, pixel-perfect animations and visuals.
Introduction
As I embark on a new side project, I've decided to explore Kotlin Multiplatform Mobile (KMM) to create a shared library that will house all business logic. This will include components like the database, app state, and network connectivity. Inspired by the BLoC architecture pattern, popular in Flutter, my goal is to adapt this pattern for use in both Kotlin and native iOS and Android environments. The cherry on top? Each platform will still boast native UIs to ensure top-notch, pixel-perfect animations and visuals.
Setting the Stage
First, a bit of setup is required. As of now, Android Studio supports KMM through a plugin, but IntelliJ IDEA Ultimate does not. This is an interesting gap in JetBrains' otherwise comprehensive tool support. Regardless, Android Studio will suffice for our needs.
Building the Library
Android
To create an Android Archive (AAR) file:
- Open the terminal and navigate to the root of your project.
- Run the command:
./gradlew clean build
- Once the build completes, you can find the AAR file in:
/{module_name}/build/outputs/aar
This AAR file contains all your Android-specific code packaged neatly.
iOS
To build an XCFramework for iOS, which allows the inclusion of binaries for multiple architectures:
- Execute the following command:
./gradlew clean assembleXCFramework
- Detailed instructions and variations of this command can be found in the Kotlin Multiplatform documentation.
- The XCFramework will be located in:
/{module_name}/build/XCFrameworks
Integrating the Library into Your Projects
Android
- Place the AAR file within the
modules
directory at the root of your Android project (e.g.,modules/sample_core.aar
). - In your module’s
build.gradle.kts
, add the following dependency:
dependencies {
implementation(files("../modules/sample_core.aar"))
}
iOS
- Copy the XCFramework into your iOS project’s directory.
- Through Xcode, navigate to your project's settings, then to "Frameworks, Libraries, and Embedded Content."
- Use the '+' button to add the XCFramework from your local filesystem.
- Import the framework in any Swift or Objective-C class where it’s needed.
Conclusion
This post covers the fundamental steps to create and integrate a Kotlin Multiplatform library into Android and iOS projects. Upcoming posts will dive deeper into implementing a database, managing network connectivity with KMM, and utilizing the BLoC pattern to handle state across platforms. Stay tuned for more insights and keep experimenting!