# Announcing the Realm Kotlin Beta: A Database for Multiplatform Apps

The Realm team is happy to announce the beta release of our Realm Kotlin SDK—with support for both Kotlin for Android and Kotlin Multiplatform apps. With this release, you can deploy and maintain a data layer across iOS, Android, and desktop platforms from a single Kotlin codebase.

:youtube]{vid=6vL5h8pbt5g}

Realm is a super fast local data store that makes storing, querying, and syncing data simple for modern applications. With Realm, working with your data is as simple as interacting with objects from your data model. Any updates to the underlying data store will automatically update your objects, enabling you to refresh the UI with first-class support for Kotlin’s programming primitives such as Coroutines, Channels, and Flows. 

## Introduction

Our goal with Realm has always been to provide developers with the tools they need to easily build data-driven, reactive mobile applications. Back in 2014, this meant providing Android developers with a first-class Java SDK. But the Android community is changing. With the growing importance of Kotlin, our team had two options: refactor the existing Realm Java SDK to make it Kotlin-friendly or use this as an opportunity to build a new SDK from the ground up that is specifically tailored to the needs of the Kotlin community. After collecting seven years of feedback from Android developers, we chose to build a new Kotlin-first SDK that pursued the following directives:

* Expose Realm APIs that are idiomatic and directly integrate with Kotlin design patterns such as Coroutines and Flows, eliminating the need to write glue code between the data layer and the UI.
* Remove Realm Java’s thread confinement for Realms and instead emit data objects as immutable structs, conforming to the prevalent design pattern on Android and other platforms.
* Expose a single Realm singleton instance that integrates into Android’s lifecycle management automatically, removing the custom code needed to spin up and tear down Realm instances on a per-activity or fragment basis.

> **Build better mobile apps with Atlas Device Sync**: Atlas Device Sync is a fully-managed mobile backend-as-a-service. Leverage out-of-the-box infrastructure, data synchronization capabilities, built-in network handling, and much more to quickly launch enterprise-grade mobile apps. [Get started now by build: Deploy Sample for Free!

## What is Realm?

Realm is a fast, easy-to-use alternative to SQLite + Room with built-in cloud capabilities, including a real-time edge-to-cloud sync solution. Written from the ground up in C++, it is not a wrapper around SQLite or any other relational data store. Designed with the mobile environment in mind, it is lightweight and optimizes for constraints like compute, memory, bandwidth, and battery that do not exist on the server side. Realm uses lazy loading and memory mapping with each object reference pointing directly to the location on disk where the state is stored. This exponentially increases lookup and query speed as it eliminates the loading of state pages of disk space into memory to perform calculations. It also reduces the amount of memory pressure on the device while working with the data layer. Simply put, Realm makes it easy to store, query, and sync your mobile data across devices and the back end.

## Realm for Kotlin developers

Realm is an object database, so your schema is defined in the same way you define your object classes. Under the hood, Realm uses a Kotlin compiler plugin to generate the necessary getters, setters, and schema for your database, freeing Android developers from the monotony of Room’s DAOs and the pain of investigating inaccurate SQL query responses from SQLite. 

Realm also brings true relationships to your object class definitions, enabling you to have one-to-one, one-to-many, many-to-many, and even inverse relationships. And because Realm objects are memory-mapped, traversing the object graph across relationships is done in the blink of an eye. 

Additionally, Realm delivers a simple and intuitive query system that will feel natural to Kotlin developers. No more context switching to SQL to instantiate your schema or looking behind the curtain when an ORM fails to translate your calls into SQL. 

```kotlin
// Define your schema - Notice Project has a one-to-many relationship to Task
class Project : RealmObject {
    var name: String = ""
    var tasks: RealmList = realmListOf()
}

class Task : RealmObject {
    var name: String = ""
    var status: String = "Open"
    var owner: String = ""
}

// Set the config and open the realm instance
val easyConfig = RealmConfiguration.with(schema = setOf(Task::class, Project::class))

val realm: Realm = Realm.open(easyConfig)

// Write asynchronously using suspend functions
realm.write { // this: MutableRealm
    val project = Project().apply {
        name = "Kotlin Beta"
    }
    val task = Task().apply {
        name = "Ship It"
        status = "InProgress"
        owner = "Christian"
    }
    project.tasks = task
    copyToRealm(project)
}

// Get a reference to the Project object
val currentProject: Project =
    realm.query(
        "name == $0", "Kotlin Beta"
    ).first().find()!!

// Or query multiple objects
vall allTasks: RealmResults = 
    realm.query().find()

// Get notified when data changes using Flows
currentProject.tasks.asFlow().collect { change: ListChange ->
    when (change) {
        is InitialList -> {
            // Display initial data on UI
            updateUI(change.list)
        }
        is UpdatedList -> {
            // Get information about changes compared
            // to last version.
            Log.debug("Changes: ${change.changeRanges}")
            Log.debug("Insertions: ${change.insertionRanges}")
            Log.debug("Deletions: ${change.deletionRanges}")
            updateUI(change.list)
        }
        is DeletedList -> {
            updateUI(change.list) // Empty list
        }
    }
}

// Write synchronously - this blocks execution on the caller thread 
// until the transaction is complete
realm.writeBlocking { // this: MutableRealm
    val newTask = Task().apply {
        name = "Write Blog"
        status = "InProgress"
        owner = "Ian"
    }

    findLatest(currentProject)?.apply {
        tasks.add(newTask)
    }
}

// The UI will now automatically display two tasks because 
// of the above defined Flow on currentProject
```
Finally, one of Realm’s main benefits is its out-of-the-box data synchronization solution with MongoDB Atlas. Realm Sync makes it easy for developers to build reactive mobile apps that stay up to date in real-time.

## Looking ahead

The Realm Kotlin SDK is a free and open source database available for you to get started building applications with today! With this beta release, we believe that all of the critical components for building a production-grade data layer in an application are in place. In the future, we will look to add embedded objects; data types such as Maps, Sets, and the Mixed type; ancillary sync APIs as well as support for Flexible Sync; and finally, some highly optimized write and query helper APIs with the eventual goal of going GA later this year.

Give it a try today and let us know what you think! Check out our samples, read our docs, and follow our repo.

>For users already familiar with Realm Java, check out the video at the top of this article if you haven't already, or our migration blog post and documentation to see what is needed to port over your existing implementation.