MongoDB Developer
Realm
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Realmchevron-right

Getting Started Guide for Kotlin Multiplatform Mobile (KMM) with Flexible Sync

Mohit SharmaPublished Jan 12, 2023 • Updated Jan 26, 2023
AndroidiOSRealmSyncKotlin
Copy Link
facebook icontwitter iconlinkedin icon
random alt
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
This is an introductory article on how to build your first Kotlin Multiplatform Mobile using Atlas Device Sync.

Introduction

Mobile development has evolved a lot in recent years and in this tutorial, we are going discuss Kotlin Multiplatform Mobile (KMM), one such platform which disrupted the development communities by its approach and thoughts on how to build mobile apps.
Traditional mobile apps, either built with a native or hybrid approach, have their tradeoffs from development time to performance. But with the Kotlin Multiplatform approach, we can have the best of both worlds.

What is Kotlin Multiplatform Mobile (KMM)?

Kotlin Multiplatform is all about code sharing within apps for different environments (iOS, Android). Some common use cases for shared code are getting data from the network, saving it into the device, filtering or manipulating data, etc. This is different from other cross-development frameworks as this enforces developers to share only business logic code rather than complete code which often makes things complicated, especially when it comes to building different complex custom UI for each platform.

Setting up your environment

If you are an Android developer, then you don't need to do much. The primary development of KMM apps is done using Android Studio. The only additional step for you is to install the KMM plugin via IDE plugin manager. One of the key benefits of this is it allows to you build and run the iOS app as well from Android Studio.
To enable iOS building and running via Android Studio, your system should have Xcode installed, which is development IDE for iOS development.
To verify all dependencies are installed correctly, we can use kdoctor, which can be installed using brew.

Building Hello World!

With our setup complete, it's time to get our hands dirty and build our first Hello World application.
Creating a KMM application is very easy. Open Android Studio and then select Kotlin Multiplatform App from the New Project template. Hit Next.
KMM Template
On the next screen, add the basic application details like the name of the application, location of the project, etc.
Enter Project Name
Finally, select the dependency manager for the iOS app, which is recommended for Regular framework, and then hit finish.
Select Dependency Manager
Once gradle sync is complete, we can run both iOS and Android app using the run button from the toolbar.
iOS app run
android app run
That will start the Android emulator or iOS simulator, where our app will run.

Basics of the Kotlin Multiplatform

Now it's time to understand what's happening under the hood to grasp the basic concepts of KMM.
Understanding project structure
Any KMM project can be split into three logic folders — i.e., androidApp, iosApp, and shared — and each of these folders has a specific purpose.
Project structure
Since KMM is all about sharing business-/logic-related code, all the shared code is written under shared the folder. This code is then exposed as libs to androidApp and iosApp folders, allowing us to use shared logic by calling classes or functions and building a user interface on top of it.
Writing platform-specific code
There can be a few use cases where you like to use platform-specific APIs for writing business logic like in the Hello World! app where we wanted to know the platform type and version. To handle such use cases, KMM has introduced the concept of actual and expect, which can be thought of as KMM's way of interface or Protocols.
In this concept, we define expect for the functionality to be exposed, and then we write its implementation actual for the different environments. Something like this:
In the above example, you'll notice that we are using platform-specific APIs like android.os or UIDevice in shared folder. To keep this organised and readable, KMM has divided the shared folder into three subfolders: commonMain, androidMain, iOSMain.
shared folder split
With this, we covered the basics of KMM (and that small learning curve for KMM is especially for people coming from an android background) needed before building a complex and full-fledged real app.

Building a more complex app

Now let's build our first real-world application, Querize, an app that helps you collect queries in real time during a session. Although this is a very simple app, it still covers all the basic use cases highlighting the benefits of the KMM app with a complex one, like accessing data in real time.
The tech stack for our app will be:
  1. JetPack Compose for UI building.
  2. Kotlin Multiplatform with Realm as a middle layer.
  3. Atlas Flexible Device Sync from MongoDB, serverless backend supporting our data sharing.
  4. MongoDB Atlas, our cloud database.
We will be following a top to bottom approach in building the app, so let's start building the UI using Jetpack compose with ViewModel.
In our viewModel, we have a method saveQuery to capture the user queries and share them with the speaker. This information is then passed on to our logic layer, RealmRepo, which is built using Kotlin Multiplatform for Mobile (KMM) as we would like to reuse this for code when building an iOS app.
Now, to save and share this information, we need to integrate it with Atlas Device Sync, which will automatically save and share it with our clients in real time. To connect with Device Sync, we need to add Realm SDK first to our project, which provides us integration with Device Sync out of the box.
Realm is not just SDK for integration with Atlas Device Sync, but it's a very powerful object-oriented mobile database built using KMM. One of the key advantages of using this is it makes our app work offline without any effort.
Adding Realm SDK
This step is broken down further for ease of understanding.
Adding Realm plugin
Open the build.gradle file under project root and add the Realm plugin.
From
To
Enabling Realm plugin
Now let's enable the Realm plugin for our project. We should make corresponding changes to the build.gradle file under the shared module.
From
To
Adding dependencies
With the last step done, we are just one step away from completing the Realm setup. In this step, we add the Realm dependency to our project.
Since the Realm database will be shared across all platforms, we will be adding the Realm dependency to the common source shared. In the same build.gradle file, locate the sourceSet tag and update it to:
From
To
With this, we have completed the Realm setup for our KMM project. If you would like to use any part of the SDK inside the Android module, you can add the dependency in Android Module build.gradle file.
Since Realm is an object-oriented database, we can save objects directly without getting into the hassle of converting them into different formats. To save any object into the Realm database, it should be derived from RealmObject class.
Now let's save our query into the local database, which will then be synced using Atlas Device Sync and saved into our cloud database, Atlas.
The next step is to create a Realm instance, which we use to save the information. To create a Realm, an instance of Configuration is needed which in turn needs a list of classes that can be saved into the database.
This Realm instance is sufficient for saving data into the device but in our case, we need to integrate this with Atlas Device Sync to save and share our data into the cloud. To do this, we take four more steps:
  1. Follow the setup wizard after signing up to create a free cluster.
  2. Create an App with App Service UI to enable Atlas Device Sync.
  3. Enable Atlas Device Sync using Flexible Sync. Select the App services tab and enable sync, as shown below. Device Sync
Now let's connect our Realm and Atlas Device Sync. To do this, we need to modify our Realm instance creation. Instead of using RealmConfiguration, we need to use SyncConfiguration.
SyncConfiguration instance can be created using its builder, which needs a user instance and initialSubscriptions as additional information. Since our application doesn't have a user registration form, we can use anonymous sign-in provided by Atlas App Services to identify as user session. So our updated code looks like this:
Now, the last step to complete our application is to write a read function to get all the queries and show it on UI.
Also, you can view or modify the data received via the saveInfo function using the Atlas UI.
Atlas UI
With this done, our application is ready to send and receive data in real time. Yes, in real time. No additional implementation is required.
Sync

Summary

Thank you for reading this article! I hope you find it informative. The complete source code of the app can be found on GitHub.
If you have any queries or comments, you can share them on the MongoDB Realm forum or tweet me @codeWithMohit.

Copy Link
facebook icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

Realm Serverless Platform Integration with No-Code Composer from AppGyver


Sep 23, 2022
Tutorial

Adding Realm as a dependency to an iOS Framework


Sep 02, 2022
Code Example

Find our Devices - A locator app built using Realm


Jun 15, 2022
News & Announcements

Realm Kotlin 0.6.0.


Oct 19, 2022
Table of Contents