Auto Added by WPeMatico

CocoaPods Support in the Kotlin Multiplatform Mobile Plugin for AppCode

Kotlin Multiplatform Mobile plugin for AppCode helps you develop applications for Android and iOS using the unified Gradle project model and provides cross-language code assistance.

CocoaPods integration now works with the latest plugin version available in our plugin repository. Just add a Pod dependency to your shared module, sync the Gradle project, import the required module in your Swift or Objective-C code, and you’ll get code assistance for all of its symbols:

KMM Code Assistance

If you have any questions or encounter any issues, please submit them to the plugin issue tracker. And don’t forget to get your free four-month AppCode personal subscription to test out the plugin for yourself!

Download KMM plugin for AppCode

Read more

Continue ReadingCocoaPods Support in the Kotlin Multiplatform Mobile Plugin for AppCode

Sample the World of KMM

One of the main benefits of Kotlin Multiplatform Mobile is its flexibility. You can use KMM in your existing or new projects, share different parts of your apps, and integrate with different UI frameworks. To find the best way to apply this flexibility in your project and maximize the benefits of using KMM, it can really help to look at how other projects have used it. Today we’ll look at the KMM sample projects that are available!

Explore a variety of KMM sample projects

There are a lot of decisions to make when first introducing KMM to your team, everything from which architecture to use to who will be writing the shared code. Sample projects are a great source of inspiration to help you make such decisions. You can look into their codebase and see how things are implemented and use them as a playground to try new things as well. Since going Alpha, the number of samples has grown and continues to grow. Here are a few exciting samples that cover different code-sharing use cases:

  • The D-KMP sample demonstrates how to fully share the ViewModel (including the navigation layer) with KMM. It implements the MVI and CQRS patterns, and uses the latest declarative UI toolkits, Compose for Android and SwiftUI for iOS.
  • The multiplatform-redux-sample shows how to build a cross-platform application with KMM and ReduxKotlin.
  • The famous people-in-space project is a great demonstration of the power of the Kotlin Multiplatform technology. In addition to sharing all the business logic and using modern mobile UI toolkits, it uses Compose Desktop, so you can run this sample application on your PC!
  • KMM production sample is an official sample from the JetBrains team. It’s a simple RSS reader that you can download from the App Store and Google Play. It’s designed to demonstrate how KMM can be used in real production projects, providing a comprehensive readme with an explanation of the architecture so you can apply the approaches in your own projects. This sample has been already migrated to the new Kotlin/Native memory manager development preview!
  • Kamp-Kit is a collection of code and tools designed to help you get started quickly. In addition to a native mobile KMM app with a small functional feature set, it also contains educational resources and guides on integrating shared code into an existing application.

All this is just the beginning! Check out the table on the KMM documentation portal to find a sample similar to what you want for your KMM project and take a deep dive into KMM right away! For example, you can find a sample that uses SQLDelight for data storage, modern declarative frameworks for the user interface, and that has the logic shared not only between mobile apps but also between a web client. 

Find the perfect KMM sample!

Become the part of the growing ecosystem

Do you have an example of how you implemented KMM that you think others could benefit from? Create your own sample!  For example, you can demonstrate how to maximize the amount of shared code or how to organize your project when you want to store native and shared parts of your application in separate repositories. Sample projects like these really help the KMM ecosystem and help us all evolve. Feel free to reach out to us and tell us about your project! We are grateful to all inspiring sample project authors and would be happy to add yours to the official list. 

Read more

Continue ReadingSample the World of KMM

Try Kotlin Multiplatform Mobile in AppCode for Free!

Hi everyone,

We recently announced a new plugin for Kotlin Multiplatform Mobile development that helps you develop applications for Android and iOS using the unified Gradle project model and provides cross-language code assistance.

Currently, this plugin is available only for AppCode, a paid IDE. We’ve decided to provide a way to try this plugin for free: just fill out this form to get four free months of a personal AppCode subscription!

Get a free AppCode trial

We hope that this additional free subscription will help those who didn’t have a chance to try the plugin during the AppCode 2021.2 EAP. Don’t forget to share your feedback with us here in the comments, in the plugin tracker, or via AppCode support!

Read more

Continue ReadingTry Kotlin Multiplatform Mobile in AppCode for Free!

Try Kotlin Multiplatform Mobile in AppCode for Free!

Hi everyone,

We recently announced a new plugin for Kotlin Multiplatform Mobile development that helps you develop applications for Android and iOS using the unified Gradle project model and provides cross-language code assistance.

Currently, this plugin is available only for AppCode, a paid IDE. We’ve decided to provide a way to try this plugin for free: just fill out this form to get four free months of a personal AppCode subscription!

Get a free AppCode trial

We hope that this additional free subscription will help those who didn’t have a chance to try the plugin during the AppCode 2021.2 EAP. Don’t forget to share your feedback with us here in the comments, in the plugin tracker, or via AppCode support!

Read more

Continue ReadingTry Kotlin Multiplatform Mobile in AppCode for Free!

Try Kotlin Multiplatform Mobile in AppCode for Free!

Hi everyone,

We recently announced a new plugin for Kotlin Multiplatform Mobile development that helps you develop applications for Android and iOS using the unified Gradle project model and provides cross-language code assistance.

Currently, this plugin is available only for AppCode, a paid IDE. We’ve decided to provide a way to try this plugin for free: just fill out this form to get four free months of a personal AppCode subscription!

Get a free AppCode trial

We hope that this additional free subscription will help those who didn’t have a chance to try the plugin during the AppCode 2021.2 EAP. Don’t forget to share your feedback with us here in the comments, in the plugin tracker, or via AppCode support!

Read more

Continue ReadingTry Kotlin Multiplatform Mobile in AppCode for Free!

Try Kotlin Multiplatform Mobile in AppCode for Free!

Hi everyone,

We recently announced a new plugin for Kotlin Multiplatform Mobile development that helps you develop applications for Android and iOS using the unified Gradle project model and provides cross-language code assistance.

Currently, this plugin is available only for AppCode, a paid IDE. We’ve decided to provide a way to try this plugin for free: just fill out this form to get four free months of a personal AppCode subscription!

Get a free AppCode trial

We hope that this additional free subscription will help those who didn’t have a chance to try the plugin during the AppCode 2021.2 EAP. Don’t forget to share your feedback with us here in the comments, in the plugin tracker, or via AppCode support!

Read more

Continue ReadingTry Kotlin Multiplatform Mobile in AppCode for Free!

Try Kotlin Multiplatform Mobile in AppCode for Free!

Hi everyone,

We recently announced a new plugin for Kotlin Multiplatform Mobile development that helps you develop applications for Android and iOS using the unified Gradle project model and provides cross-language code assistance.

Currently, this plugin is available only for AppCode, a paid IDE. We’ve decided to provide a way to try this plugin for free: just fill out this form to get four free months of a personal AppCode subscription!

Get a free AppCode trial

We hope that this additional free subscription will help those who didn’t have a chance to try the plugin during the AppCode 2021.2 EAP. Don’t forget to share your feedback with us here in the comments, in the plugin tracker, or via AppCode support!

Read more

Continue ReadingTry Kotlin Multiplatform Mobile in AppCode for Free!

Multiplatform Gradle Plugin Improved for Connecting KMM Modules

If you use Kotlin Multiplatform Mobile (KMM) for sharing code between iOS and Android, you will at some point have to decide how you will deliver the shared module to your platform projects. While Android integration is smooth out of the box, iOS integration can require some additional setup. In this post, you will learn how to use the latest Kotlin features to easily connect the KMM module to your iOS projects and simplify your project build configuration when the shared and iOS source code from your project are in the same location.

Learn more about KMM

Ways to connect the KMM module to the iOS project

There are a couple of ways to integrate shared KMM modules into iOS applications. If the source code of the KMM module and Xcode project are in the same location, one of the approaches is to use the CocoaPods integration. If you don’t want to use CocoaPods, another approach is to expose the iOS framework to the Xcode project that the iOS application is built from by using a special Gradle task. 

This task uses the configuration of the iOS application project to define the build mode (debug or release, device or simulator target) and provides the appropriate framework version to the specified location. The Xcode project is configured so that the task executes upon each build to provide the latest version of the framework for the iOS application.

Old approach: manual

packForXcode

task

Before Kotlin 1.5.20, you had to provide this Gradle task and configure the XCode project manually, or you could use KMM Plugin for Android Studio project wizards, which generated the required

packForXcode

Gradle task and configured the XCode project to use this task for the build.

New approach: integrated

embedAndSignAppleFrameworkForXcode

task

Starting from Kotlin 1.5.20, the Kotlin Multiplatform Gradle Plugin provides an

embedAndSignAppleFrameworkForXcode

task that can be used from Xcode to connect the KMM module to the iOS part of your project. This task can be used only for integration purposes and is only for Xcode, not for CLI.  If you want to create a new KMM project, consider using the KMM plugin for Android Studio project wizard. It allows you to create a KMM project with a suitable iOS integration option – either the Cocoapods dependency manager or a regular framework that will use the new

embedAndSignAppleFrameworkForXcode

in the generated project configuration.

KMM Plugin for Android Studio Project Wizard

If you have an existing project that uses the

packForXcode

task, migrate to

embedAndSignAppleFrameworkForXcode

. This will:

How to migrate to the new approach

  1. Delete the
    packForXcode

    task from your

    build.gradle(.kts)

    file of the KMM module.

  2. In the Xcode Run Script build step, change
    packForXcode

    to

    embedAndSignAppleFrameworkForXcode

    and remove all the passed flags. The task will use the Xcode environment configuration and build only the needed artifact automatically.

  1. In Xcode build steps, remove everything related to the KMM framework (there should be no mention of it in the Link Binaries or Embed Frameworks sections).
  2. In Xcode build settings, set Other Linker flags:
    $(inherited) -framework shared
  1. In Xcode build settings, set Framework Search Path:
    $(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)

This is an integrational task, and it is visible only from Xcode. If you want to assemble the iOS framework manually, you should use the

link(debug|release)FrameworkIos

Gradle task

For additional reference, check out the commit with the migration diff from the sample project.

If you run into any problems

Your feedback and ideas have a big influence on the decisions we make about new KMM features. Please share your experience with using Kotlin Multiplatform in the user survey. Don’t miss this chance to shape the future of technology!

Read more

Continue ReadingMultiplatform Gradle Plugin Improved for Connecting KMM Modules

Kotlin Multiplatform Mobile for AppCode

Hi everyone,

Today we’re expanding our Kotlin Multiplatform Mobile ecosystem by introducing the Kotlin Multiplatform Mobile (KMM) plugin for AppCode.

By using this plugin you can:

  • Specify the structure of the iOS part of your KMM project in the same way you specify the Android one. We’ve created a special Gradle DSL for describing iOS projects that does not require having
    .xcodeproj

    or

    .xcworkspace

    .

  • Write Objective-C/Swift and Kotlin code in one IDE. Cross-resolve between Objective-C/Swift and Kotlin works automatically so you can easily jump from the common Kotlin code to its usages in the iOS-specific part. It goes without saying that code completion and code highlighting for Objective-C/Swift are available as well.

The goal is to maintain the project structure in one place and unify the layout of iOS and Android project parts, while preserving all the flexibility that Kotlin Multiplatform Mobile provides.

Pre-requisites

In addition to Xcode, which is required to work with the iOS part, you will need to download the Android SDK. It should be automatically identified by the plugin and set in

local.properties

:

Android SDK directory

Create a project

In the

File | New Project

wizard, select the KMM Application template:

New project

AppCode will create a minimal project with iOS and Android “Hello world!” applications. As you can see, the whole iOS application is inside the apple folder. The following minimal DSL is used to describe the project in the corresponding

build.gradle.kts

:

apple {
    iosApp {
        productName = "mpptest"

        sceneDelegateClass = "SceneDelegate"
        launchStoryboard = "LaunchScreen"
      
        dependencies {
            implementation(project(":shared"))
        }
    }
}

Here we have some predefined properties, such as

productName

or

scenedelegateClass

in the

iosApp

target, that speak for themselves. We can also specify any custom build settings or product info keys in the following way:

productInfo["NSAppTransportSecurity"] = mapOf("NSAllowsArbitraryLoads" to true)
buildSettings["OTHER_LDFLAGS"] = "some_value"

Write the code

The KMM plugin for AppCode provides the same code assistance as the Kotlin/Native plugin did previously. Cross-resolve between Objective-C/Swift and Kotlin works automatically and does not require rebuilding the project:

Code assistance

Build, run, and debug

You can run and debug the Android or iOS part of your application by selecting the corresponding run configuration:

Run configurations

To build the iOS part, AppCode generates a temporary Xcode project and invokes the Xcode build system, so you can be sure that our Gradle project model will work the same as a regular Xcode project does.

If you set a breakpoint inside the shared code or the platform-specific part, the IDE will recognize them and will stop during debugging:

Debug

Test your app

The following test configurations are created automatically:

  • Common Tests – for tests in the commonTest module. We can run them on the local JVM (since unit tests for Android do not have to be run on the simulator) or one of the iOS devices/simulators (since even unit tests on iOS are executed in the simulator).
  • Android Library Tests – for tests in androidTest package (platform-specific tests written in Kotlin for Android).
  • iOS Library Tests – for tests in the iosTest package (platform-specific tests written in Kotlin for iOS).
  • iOS App Tests – for tests in the iosAppTest package, where any iOS tests can be stored.

You can run and debug them (as well as separate tests):

Tests

Supported platforms

Currently, only iOS application and test targets are supported. Android targets are supported in the same way as in Android Studio.

Future plans

We’re working on a solution that will allow you to hook up an existing

.xcodeproj

or

.xcworkspace

to the Gradle DSL to make it possible to easily connect existing Xcode projects with the common and Android parts.

We’re also considering integrating some platform-specific IDE functionality. But as a first step, we’re focusing on the language support and project model management to give you a first-class experience for writing your business logic.

That’s it! We hope this new plugin will help you develop your applications easier and faster. You can try it with AppCode EAP builds that are already available for download.

Should you have any feedback for us, don’t hesitate to use the comments section below, submit an issue or feature request to the plugin tracker, or ping AppCode support. Thank you!

Download KMM plugin for AppCode

Continue ReadingKotlin Multiplatform Mobile for AppCode

Create Your KMM Library

Since the release of Kotlin Multiplatform Mobile about 9 months ago, more and more developers have decided to give it a try and start to share their code between mobile platforms. Some do this in their free time while working on pet projects. Some integrate KMM into existing apps. And some even base their brand new applications on the KMM technology. 

The technology is already helping many developers all across the world, but its ecosystem has plenty of space to build on and for new libraries to be added. We would like to encourage you to help build this ecosystem and create libraries in order to help more developers realize the benefits of sharing code between mobile platforms with Kotlin.

Create Your KMM Library

In this article, we will provide a brief overview of the most popular Kotlin Multiplatform Mobile libraries and shed some light on what motivated the authors to create them and hopefully inspire you to contribute yourself.

SQLDelight, Alec Strong

I started writing SQLDelight because we weren’t happy with the existing libraries for working with SQLite on Android. We had the idea to write an IntelliJ/Gradle plugin pair to make working with SQLite easier, so we gave it a shot and really liked the result. It was also a great opportunity to try Kotlin out before using it in our Android app (this was all the way back in 2015), and because it had no product-specific components we kept it open source.

At its core, SQLDelight is about code generation. Although the first version generated Java code that was extremely hard to use. So about two years ago, we began rewriting the library from scratch with pure Kotlin-generated code, and we thought this would be a great opportunity to keep it platform-agnostic. Because SQLDelight’s only required dependency is SQLite, which itself is available on essentially every platform, it made sense to embrace KMM. We didn’t make this choice with any particular use case in mind, but rather with the knowledge that we were protecting ourselves from doing too much in the library. Working on 10 platforms forces us to keep our level of abstraction very close to that of SQLite itself.

In the last few years, SQLDelight has turned into a massive community effort, so much so that the majority of the IDE features are now contributed, the entire native stack is contributed, other SQL dialect support is contributed, the js driver was contributed, and an enormous amount of other features, improvements, and bug fixes all come from external contributors. We’ve received a lot of support from the KMM community, which has helped get SQLDelight to where it is today. I’m really glad we chose to embrace KMM when we did, since it helped shape SQLDelight into a well-defined, single-purpose library, and brought many community contributions that have helped the library across all platforms.

Decompose, Arkadii Ivanov

Decompose contains Kotlin Multiplatform lifecycle-aware business logic components (aka BLoC) with routing functionality and a pluggable UI. The library provides a simple way to split code, shared or unshared, into decoupled reusable components. The library also provides navigation between components with strongly typed arguments, so this logic can be shared as well. Decompose works best with declarative UI frameworks, such as Jetpack Compose for Android/Desktop, SwiftUI, React, and so on. However, common Android Views are also supported (experimental).

KMM allows developers to share the parts of code they want to share, and it doesn’t force them to stop at the business logic. That was my motivation for trying to cover the missing part in the ecosystem of the Kotlin Multiplatform libraries – navigation and componentization. This was also a good chance to play with declarative UI frameworks and see how they work with Kotlin Multiplatform.

You can listen to a detailed explanation of the Decompose library from Arkadii Ivanov in this episode of Talking Kotlin. 

Realm Kotlin Multiplatform SDK, Nabil Hachicha

Realm is a database designed from the ground up for mobile development, available on iOS and Android. It’s open-source, easy-to-use, and helps mobile developers build better apps faster.

With the emergence of Kotlin/Native and the Multiplatform initiative, developers using the Java version of Realm started wondering about the possibility of supporting Realm in a Multiplatform context. This need was driven primarily by the prospect of writing a shared persistence logic across iOS/Android, since some users using Realm were duplicating the same logic across the Cocoa SDK and the Java SDK on their products.

We also believe that the bottom-up approach to building a cross-platform application is more appealing and less risky for developers. Business logic, network, serialization, and persistence are more likely to be shared between platforms than the UI is, so we wanted to position Realm as an option for KMM developers.

Recently we decided to write a Kotlin-first Realm SDK in order to integrate more seamlessly with current reactive frameworks from Kotlin’s structured concurrency libraries. At the same time, we wanted to build it as a Multiplatform library to cater to existing Java users while also opening the door for developers who might want to try the new cross-platform paradigm.

For more details check out the “Realm Kotlin Multiplatform SDK” article on our blog and the episode of the Talking Kotlin podcast featuring the authors of the project.

Multiplatform Settings, Russell Wolf

Multiplatform Settings is a multiplatform key-value storage library that allows developers to persist simple data in their applications. It wraps around typical platform key-value APIs to make migration and interoperation with pre-existing platform-specific code using these APIs easier. The first version was publicly announced in May 2018, making it one of the first community-developed multiplatform libraries. While it started as just a mobile library targeting Android and iOS (long before KMM was a phrase anyone was using), it has since grown to include implementations on JS, the JVM, and native macOS and Windows.

My biggest inspiration for jumping into library development came from talks and articles by Kevin Galligan (long before I joined Touchlab). I’d been loosely following the early development of Kotlin/Native in 2017 and was attracted to the idea that we might someday use it to share Kotlin code to iOS. Kevin highlighted how, as developers were starting to write multiplatform apps, there would be a need for libraries for them to make use of, and pointed out how it was a good moment to get in early and make a significant impact before the ecosystem got crowded. 

While I’d already begun to get involved in community events like meetups, this was my first major open source contribution. It opened a lot of doors, leading to my first conference talk at Droidcon NYC 2018, with others to follow. It’s a really nice feeling when you move from sitting in the audience at events to being someone other people recognize and ask questions to. It’s also been a great resume-booster, helping me short-cut the job interview process more than once, since I had public demonstrations of my technical ability.

Ktor, Hadi Hariri

The goal of Ktor is to provide an end-to-end multiplatform application framework for connected applications. Currently, JVM client and server scenarios are supported, as well as JavaScript, iOS, and Android clients, and we are working on bringing server facilities to native environments, and client facilities to other native targets.

We developed Ktor to give the Kotlin community a library that made use of Kotlin’s DSL capabilities as well as coroutines. Built from the ground up using Kotlin, Ktor provides developers with the ability to create not only server-side applications, but also client-side ones. It is used heavily in Kotlin Multiplatform Mobile applications that require HTTP connectivity, as the client supports Kotlin/Native as well as Kotlin/JVM and Kotlin/JS.
Joining many other libraries that are Kotlin Multiplatform, Ktor provides developers the ability to focus on their application logic and business needs, as opposed to worrying about infrastructure code. 

Conclusion

Kotlin Multiplatform Mobile is growing increasingly popular, with big companies and independent developers adopting it in their user-facing apps. As the number of developers using KMM to share code between mobile platforms increases, the demand for libraries will rise proportionally.

This provides a great opportunity for anyone who would like to contribute. Join the community of library authors by following our special series of articles that explain all the aspects you will need to know about creating your KMM library.

If you still not sure where best to direct your efforts, you may consider working in one of these areas:

  • Testing and code coverage
  • DI and mocking
  • IO

We encourage you to build libraries, share your knowledge, and help other KMM developers achieve professional success. There are a lot of open needs in the community, and your involvement will be truly appreciated!

Create Your KMM Library

Read and watch more: 

Learn more from the Kotlin and KMM docs:

Continue ReadingCreate Your KMM Library

What’s new in KMM since going Alpha

Kotlin Multiplatform Mobile (KMM), an SDK for cross-platform mobile development, went Alpha in August 2020. Over the past 9 months, the KMM ecosystem has been rapidly evolving:

  • Each new Kotlin version comes with features and improvements that enhance the multiplatform development experience.
  • KMM development tools, such as the KMM Plugin for Android Studio, are constantly receiving updates to make the process of creating cross-platform mobile applications more efficient and enjoyable.
  • The community is actively contributing to the ecosystem by producing useful libraries, creating instructive sample projects, and sharing their experience of using KMM in production.

Please read on for an overview of the main ecosystem highlights since going Alpha so that you don’t miss any important updates. Or if you can’t wait to get your first hands-on experience, visit the KMM documentation portal to learn more and try it out!

Get started with KMM


In this blog post, you will find an overview of:

What’s new in the KMM Plugin?

The KMM plugin for Android Studio can help you develop cross-platform applications. It lets you create new cross-platform mobile apps in just a few clicks and is tightly integrated with the iOS development ecosystem.

Stable and customizable integration with iOS

With the KMM Plugin you can run, test, and debug the iOS part of your application on iOS targets straight from Android Studio. Since the first release of the plugin, its iOS integration has become much more stable and configurable, and it now supports the latest iOS tooling. See the complete list of implemented iOS integration improvements.

Flexible project wizards

The KMM Plugin is also an essential tool for taking your first steps with KMM. You can use the plugin’s handy wizards to quickly create a new multiplatform project or add a multiplatform module to your existing project.

The latest plugin version provides the ability to use the Cocoapods integration for new KMM projects and modules. All you need to do is provide an additional KMM module description, and the plugin will generate all the required configuration code.

For a complete list of the new features and improvements in the KMM Plugin, along with the installation instructions and compatibility information, please visit the KMM Plugin releases page.

What’s new in Kotlin for KMM?

KMM is based on the multiplatform capabilities of Kotlin and uses Kotlin/JVM and Kotlin/Native to produce the platform artifacts – .jar for Android and .framework for iOS. Every Kotlin update improves the developer experience of building cross-platform mobile apps with KMM.

Better iOS integration with Kotlin/Native improvements

The Kotlin/Native team is heavily focused on the most awaited feature in the KMM community – the new memory management approach for Kotlin Native. We plan to present the development preview of the new memory management design by the end of summer 2021. Read the detailed status of this project in the Kotlin/Native Memory Management Update blog post.

While we’ve made significant progress in implementing the new memory management approach, we have given the other features of iOS development with Kotlin/Native our attention as well:

Stable tooling for your Multiplatform projects

Tools must be stable for you to enjoy working on any kind of project. After KMM went Alpha and a number of new multiplatform features were introduced, the Kotlin Multiplatform team focused on improving the frontend and IDE import stability for multiplatform projects. We’ve fixed many issues leading to “red code” in the IDE while working with multiplatform projects. We are going to continue improving the multiplatform developer experience, and to do this well we need your feedback. If you can spare a few minutes, please report any issues you find to YouTrack, our issue tracker.

Of course, these are just the main highlights. To see an informative summary of all the new features Kotlin provides for developing multiplatform mobile applications, please see What’s new in Kotlin for KMM in the KMM documentation portal. The page is being updated with each new Kotlin version so you won’t miss any important news!

What’s new in the community? 

The community is the heart of any technology ecosystem. You really are the greatest source of inspiration and feedback for us! Since the first release, developers worldwide have been supporting KMM ecosystem development by sharing their experience of using KMM in their production projects and creating useful libraries and sample projects.

The growing number of KMM libraries

The number of KMM libraries is constantly growing, which means you can select the ones that best fit your project requirements:

  • Realm, an easy-to-use open-source local database, now has a new Kotlin Multiplatform SDK. Read about the key design principles of the new SDK development. 
  • Decompose can help you share more code with KMM. Decompose provides Kotlin Multiplatform lifecycle-aware business logic components with routing functionality and a pluggable UI. Since KMM is flexible and allows you to choose how much of your codebase you want to share, you don’t have to limit its use to just your project’s core and business layers, and libraries like Decompose can help you achieve that goal.

KMM developers have many more needs waiting to be addressed, which means there are lots of opportunities for library authors. Consider learning how to build and publish a multiplatform library and joining this rapidly growing ecosystem!

New sample projects

Sample projects can be very helpful for getting your first hands-on experience with a technology. Thanks to an awesome community effort so far, you can choose a sample project based on your code-sharing scenarios, or play with them all:

  • The D-KMP sample demonstrates how to fully share the ViewModel (including navigation layer) with KMM, implements MVI and CQRS pattern, and uses the latest declarative UI toolkits, Compose for Android and SwiftUI for iOS.
  • The multiplatform-redux-sample shows how to build a cross-platform application with KMM and ReduxKotlin.
  • The famous people-in-space project is a great demonstration of the full power of Kotlin Multiplatform technology. In addition to sharing all the business logic and using modern mobile UI toolkits, it uses Compose Desktop, so you can run this sample application on your PC!

The latest Kotlin Multiplatform User Survey showed us that more complex samples was the most popular request from the community, which is why we’ve introduced an official KMM production sample from the KMM team. It’s a simple RSS reader that you can download from the App Store and Google Play. Designed to demonstrate how KMM can be used in real production projects, it provides a comprehensive readme with an explanation of the architecture so you can apply the approaches in your projects.

New stories of teams benefiting from KMM

Sharing code between mobile platforms with KMM is becoming common among companies and individual developers all around the world:

  • Netflix switched to Kotlin Multiplatform Mobile to optimize their studio app for reliability and increase its delivery speed.
  • Philips is using KMM to become faster at implementing new features. They have also achieved more interaction between Android and iOS developers in their team.
  • KMM is helping Down Dog launch features simultaneously on all platforms, boost development speed, and reduce the number of bugs. The team has even moved the majority of their iOS platform code from Swift to Kotlin; their entire project is now in Kotlin with the exception of just five Swift files.

Check out the case study section of the KMM portal for more inspirational stories from companies of all calibers as well as individual developers.

What’s new on the KMM portal?

We continue to develop the documentation portal to be your daily helper when working with KMM:

  • The new FAQ page is a good starting point for your KMM journey. It includes answers to the most commonly asked questions, such as how to work with KMM on Windows. If your question is not covered, let us know!
  • The new step-by-step guide will help you make your existing Android application cross-platform and working on both Android and iOS. Don’t wait until you begin a new project to enjoy the advantages of the cross-platform approach!

Reading documentation is not the only way to become familiar with the KMM. The new “Kotlin Multiplatform Multiverse” series of videos on the Kotlin YouTube channel covers such getting started topics as creating a new project and using Ktor for networking, so you can start deep-diving into KMM from the comfort of your couch.

What’s next?

That was an intense nine months! However, the best is yet to come, as KMM remains one of the key priorities of the Kotlin team.

The next important and heavily awaited milestone is moving KMM to Beta. We are working on a detailed plan for this and will publish a separate blog post about what KMM-related tasks will be completed before the Beta announcement. Most of them, including Support the Apple Silicon target in the Kotlin Multiplatform tooling and Prototype a new garbage collector, are in progress. See the Kotlin roadmap for more information on our current priorities.

We’re very happy to see the community growing and KMM being picked up by more and more companies all over the world. Join our mobile cross-platform adventure today!

Get started with KMM

Read and watch more

Watch Kotlin on YouTube:

Read the Kotlin blog:

Learn more from the Kotlin and KMM docs:

Continue ReadingWhat’s new in KMM since going Alpha

Realm Kotlin Multiplatform SDK

Nabil Hachica, Android Engineer, from MongoDB Realm shares their story of creating a pure Kotlin-first SDK for use by developers.

Realm is an open-source, easy-to-use local database that helps mobile developers to build better apps faster. It launched 8 years ago with the release of the Realm Java SDK, and since then we’ve worked to make sure our API is always improving to reflect what mobile developers need.

As Kotlin has grown to become the recommended language for building Android apps, we’ve made iterative improvements to our Realm Java SDK to make sure the API is compatible. But even with various releases over the past few years — via providing helper extension functions to improve using the Realm API with Kotlin — we knew Realm would ultimately benefit from the design and implementation of a pure Kotlin-first SDK for use by developers.

In the post, we take you through what motivated the Realm Engineering team’s decision to build a new SDK from the ground-up, and we share some of the key design principles that guided the development of Realm’s Kotlin Multiplatform SDK.

Background

As usage of Kotlin grew among Android developers, Realm’s engineering team started to use Kotlin in our testing environment. This led to introducing helper functions like Query with generic type; executeTransactionAwait – which runs transactions inside coroutines — and JSR305 annotation to improve the strict null-safety type system with Kotlin.

But even with this work, there were still architectural shifts that were difficult to solve, like users adopting unidirectional dataflows based on immutability. The wider Realm community also asked us to provide a more idiomatic Kotlin API that would enable a type safe query builder, among other API improvements. We knew some of these enhancements would require a fundamental refactoring and we wanted to meet our users’ needs. So Realm’s Engineering team started to design and implement a pure Kotlin first SDK for the mobile ecosystem.

Why a Multiplatform Library?

At the same time we began to lay the foundation of our Kotlin SDK, Kotlin Multiplatform started to mature, and we quickly realized we should build Realm’s new Kotlin SDK as a Multiplatform library. There were surprisingly few multiplatform libraries for the persistence layer, and as a multiplatform mobile database, we knew Realm could help fill this gap for developers. We had an opportunity to allow Kotlin developers to build cross platform applications in the same way that Realm’s developers use our React Native and Xamarin SDKs today.

Challenges

Porting the existing Realm-Java code to work on Multiplatform was an interesting (and challenging) task for Realm’s engineers because we currently use some technologies that are platform dependent.

To define a Realm schema, we use the annotation processor to generate a proxy class and then use the Gradle Transform API to do bytecode weaving with Javassist. Both tools are Kotlin JVM specific and are not compatible with Kotlin/Native.

Similarly, Reflection is only partially supported on Kotlin/Native, so any API design based on dynamic runtime instantiation would simply not work — like the Class.forName or class.newInstance primitives.

And, concurrency and the memory model are fundamentally different between platforms. The Kotlin/JVM has a Garbage Collector, whereas Kotlin/Native relies on reference counting with a cyclic collector.

To successfully build a multiplatform Kotlin Native SDK for Realm, we’d need to figure out how to re-architect the SDK in a way that would address these challenges.

The Solution


Note from the Kotlin team: Compiler plugins and compiler internal API are not stable yet and will likely change in the future.


Compiler Plugin to the Rescue

Realm’s engineering team quickly decided we would need to build our own fully-fledged compiler plug-in because existing options posed too many constraints.

The Kotlin Symbol Processing API is limited to generating new Kotlin code instead of modifying existing classes, meaning it wouldn’t suit our needs. Realm had used the Kotlin Annotation processor (KAPT) in our Kotlin support for the Realm Java SDK, but it didn’t have a native annotation processing system. Instead, the Realm Java SDK generates Java stubs containing all the declarations and annotations without the methods body. It then runs the Java annotation processor on those stubs, which feeds back to KAPT and Kotlin compiler for another round. This makes compilation and refactoring slow, and isn’t available for Kotlin/Native.

At a high level, the Realm compiler plugin‘s main goal is to make defining Realm models as simple as constructing a regular Kotlin class. This is achieved by modifying the Intermediate Representation (IR) of the compiled Kotlin code in order to change the behaviour of the property accessor (getters and setters).  Once this is done a developer can now call Realm’s runtime APIs so that read/writing changes the value of the property instead of the backing field. This is done using a Lowering pass on the IR.

The other task of the compiler plugin is to collect all Realm model classes in order to automatically create a schema definition of a Realm. Since the Compiler plugin API was not yet stable and documented (1.4.30 makes JVM IR Beta stable), we reverse engineered the IR code we needed to write in order to obtain the desired generated code.

Here’s what that looks like:

First, we write the Kotlin code we want the compiler to generate in a classic Kotlin/JVM project. Then we add the compiler flag to use IR and to dump the content of the IR.

This will dump a text file containing the IR code generated by the compiler before transforming it into JVM ByteCode.  We then use this IR dump to work out what IR API calls we need to use to produce the desired output. We also use kotlin-compile-testing library to unit test the IR output from the Realm compiler plugin that matches the expected IR.

Releasing Native Resources

Under the hood the Realm SDKs use a C++ storage engine. The compiler plugin adds infrastructure to link the Kotlin objects with the underlying C objects by adding a synthetic native pointer property. This holds the value of the C/ C++ pointer, allowing access to the underlying persisted value inside the storage engine.

In order to avoid leaking memory, the native pointer needs to be closed when the original Kotlin object goes out of scope.
Since Kotlin/JVM and Kotlin/Native have different memory models, we decided to use two approaches. For Kotlin/JVM we rely on the same technique we use in the current Realm-Java SDK, which is based on the usage of the reference API to track pointers that need to be cleaned once their original Java counterpart is eligible for GC.




For more information about reference API and phantom reference check out this excellent talk by Bob Lee

Kotlin/Native doesn’t have a Garbage collector. It uses reference counting with a cycle collector instead. Recently the Kotlin/Native team introduced the Cleaner API (see https://github.com/JetBrains/kotlin-native/pull/4362). This API can be used similarly to a Finalizer/Destructor block that runs after the encompassing object has been disposed of. We use this API to perform cleanups and free native pointers.

Encapsulating the native pointers in an object with the above deallocation strategies, which hook into the normal memory management, frees us from handling explicit deallocations where we use native pointers.

Native code abstraction

Accessing the custom C++ storage engine used by the Realm SDKs varies between Kotlin/JVM and Kotlin/Native. To simplify this, we added a C layer on top, which makes it easy to use tools like cinterop to interface and generate Kotlin stubs. The C layer also allowed us to avoid writing manual JNI code to access the C++ layer, thanks to SWIG tool that generates the corresponding Java and JNI stubs.

We also leveraged the expect/actual mechanism from Kotlin Multiplatform to build a module that hides the specifics of accessing Cinterop and SWIG layers in a platform agnostic manner. This allowed us to focus the design of the library API in a platform-independent way, and to do it in another module that will become the user facing public API.

This process encourages to think about features — like querying and writing to the database — in a way that’s not platform-specific.

Any platform dependent implementation details — like cleaning up native resources — do use different fundamentals per-platform (Garbage Collector for Kotlin/JVM and the Cleaner API for Kotlin/Native). This is the type of feature that should be kept inside the Native Module Abstraction layer and not be implemented in the public library module.

By isolating these low level constructs in a separate Multiplatform module, we managed to scale the development of the new Kotlin SDK within the Realm team. All the low level building blocks are isolated behind an internal platform agnostic API. This also opens up API contributions from the community without worrying about the inherent complexity of C/C++, Kotlin/Native, or JNI.

Conclusion

Now, we’re proud to say that Realm’s engineering team managed to bootstrap the new Realm Kotlin SDK as a Multiplatform library. We believe that the infrastructure is in place to encourage other authors to build Multiplatform libraries, too.

Of course, as an alpha release, we’re still polishing elements of the solution. Realm engineering has been working in lockstep with the team at JetBrains, and we have full confidence that improvements will land soon.
As we keep working, we’d love your feedback. Try the new Realm Kotlin SDK out at https://github.com/realm/realm-kotlin, and join our discussion around the design of upcoming features here. We want your opinions and suggestions as we keep building.

Author: Nabil Hachica, Android Engineer, MongoDB Realm

Continue ReadingRealm Kotlin Multiplatform SDK

End of content

No more pages to load