• Stars
    star
    942
  • Rank 48,525 (Top 1.0 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 5 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Kotlin Multiplatform and Android SDK for the Realm Mobile Database: Build Better Apps Faster.
realm by MongoDB

Gradle Plugin Portal Maven Central Kotlin License

Realm is a mobile database that runs directly inside phones, tablets or wearables.

This repository holds the source code for the Kotlin SDK for Realm, which runs on Kotlin Multiplatform and Android.

Why Use Realm

  • Intuitive to Developers: Realm’s object-oriented data model is simple to learn, doesn’t need an ORM, and lets you write less code.
  • Built for Mobile: Realm is fully-featured, lightweight, and efficiently uses memory, disk space, and battery life.
  • Designed for Offline Use: Realm’s local database persists data on-disk, so apps work as well offline as they do online.
  • MongoDB Atlas Device Sync: Makes it simple to keep data in sync across users, devices, and your backend in real-time. Get started for free with a template application and create the cloud backend.

General Availability

The Realm Kotlin SDK is GA.

Documentation can be found here.

Sample projects can be found here.

If you are upgrading from a previous beta release of Realm Kotlin, please see the CHANGELOG for the full list of changes.

If you are migrating from Realm Java, please see the Migration Guide.

Usage

Installation

Installation differs slightly depending on the type of project and whether or not you are using Device Sync. See the details in the documentation:

Also pay attention to restrictions on which versions of Kotlin and other dependencies that are supported. You can read more in the version compatibility matrix.

Define model

Start writing your database logic by first defining your model.

class Person : RealmObject {
    var name: String = "Foo"
    var dog: Dog? = null
}

class Dog : RealmObject {
    var name: String = ""
    var age: Int = 0
}

Open Database

Define a RealmConfiguration with the database schema, then open the Realm using it.

// use the RealmConfiguration.Builder() for more options
val configuration = RealmConfiguration.create(schema = setOf(Person::class, Dog::class)) 
val realm = Realm.open(configuration)

Write

Persist some data by instantiating the model object and copying it into the open Realm instance.

// plain old kotlin object
val person = Person().apply {
    name = "Carlo"
    dog = Dog().apply { name = "Fido"; age = 16 }
}

// Persist it in a transaction
realm.writeBlocking { // this : MutableRealm
    val managedPerson = copyToRealm(person)
}

// Asynchronous updates with Kotlin coroutines
CoroutineScope(context).async {
    realm.write { // this : MutableRealm
        val managedPerson = copyToRealm(person)
    }
}

Query

The query language supported by Realm is inspired by Apple’s NSPredicate, see more examples here

// All persons
import io.realm.kotlin.ext.query

val all = realm.query<Person>().find()

// Persons named 'Carlo'
val personsByNameQuery: RealmQuery<Person> = realm.query<Person>("name = $0", "Carlo")
val filteredByName: RealmResults<Person> = personsByNameQuery.find()

// Person having a dog aged more than 7 with a name starting with 'Fi'
val filteredByDog = realm.query<Person>("dog.age > $0 AND dog.name BEGINSWITH $1", 7, "Fi").find()

// Observing changes with Coroutine Flows
CoroutineScope(context).async {
    personsByNameQuery.asFlow().collect { result: ResultsChange<Person> ->
        println("Realm updated: Number of persons is ${result.list.size}")
    }
}

Update

// Find the first Person without a dog
realm.query<Person>("dog == NULL LIMIT(1)")
    .first()
    .find()
    ?.also { personWithoutDog ->
        // Add a dog in a transaction
        realm.writeBlocking {
            findLatest(personWithoutDog)?.dog = Dog().apply { name = "Laika"; age = 3 }
        }
    }

Delete

Use the result of a query to delete from the database.

// delete all Dogs
realm.writeBlocking {
    // Selected by a query
    val query = this.query<Dog>()
    delete(query)

    // From a query result
    val results = query.find()
    delete(results)

    // From individual objects
    results.forEach { delete(it) }
}

Observing data changes

Realm support asynchronous observers on all its data structures.

Realm

A Realm can be observed globally for changes on its data.

realm.asFlow()
    .collect { realmChange: RealmChange<Realm> ->
        when (realmChange) {
            is InitialRealm<*> -> println("Initial Realm")
            is UpdatedRealm<*> -> println("Realm updated")
        }
    }

RealmObject

Realm objects can be observed individually. A list of the changed field names is provided on each update.

person.asFlow().collect { objectChange: ObjectChange<Person> ->
        when (objectChange) {
            is InitialObject -> println("Initial object: ${objectChange.obj.name}")
            is UpdatedObject -> 
                println("Updated object: ${objectChange.obj.name}, changed fields: ${objectChange.changedFields.size}")
            is DeletedObject -> println("Deleted object")
        }
    }

RealmLists

Realm data structures can be observed too. On RealmList on each update you receive what positions were inserted, changed or deleted.

person.addresses.asFlow()
        .collect { listChange: ListChange<String> ->
            when (listChange) {
                is InitialList -> println("Initial list size: ${listChange.list.size}")
                is UpdatedList -> 
                    println("Updated list size: ${listChange.list.size} insertions ${listChange.insertions.size}")
                is DeletedList -> println("Deleted list")
            }
        }

RealmQuery

Query results are also observable, and like RealmList on each update, the inserted, changed and deleted indices are also provided.

realm.query<Person>().asFlow()
    .collect { resultsChange: ResultsChange<Person> ->
        when (resultsChange) {
            is InitialResults -> println("Initial results size: ${resultsChange.list.size}")
            is UpdatedResults -> 
                println("Updated results size: ${resultsChange.list.size} insertions ${resultsChange.insertions.size}")
        }
    }

RealmSingleQuery

Single element queries allow observing a RealmObject that might not be in the realm.

realm.query<Person>("name = $0", "Carlo").first().asFlow()
    .collect { objectChange: SingleQueryChange<Person> ->
        when (objectChange) {
            is PendingObject -> println("Pending object")
            is InitialObject -> println("Initial object: ${objectChange.obj.name}")
            is UpdatedObject -> 
                println("Updated object: ${objectChange.obj.name}, changed fields: ${objectChange.changedFields.size}")
            is DeletedObject -> println("Deleted object")
        }
    }

Next: head to the full KMM example.

Using Snapshots

If you want to test recent bugfixes or features that have not been packaged in an official release yet, you can use a -SNAPSHOT release of the current development version of Realm via Gradle, available on Maven Central

Groovy

// Global build.gradle
buildscript {
    repositories {
        google()
        mavenCentral()
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots'
        }
    }
    dependencies {
        classpath 'io.realm.kotlin:gradle-plugin:<VERSION>'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots'
        }
    }
}

// Module build.gradle

// Don't cache SNAPSHOT (changing) dependencies.
configurations.all {
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}

apply plugin: "io.realm.kotlin"

Kotlin

// Global build.gradle

buildscript {
    dependencies {
        classpath("io.realm.kotlin:gradle-plugin:<VERSION>-SNAPSHOT")
    }
}

repositories {
    google()
    mavenCentral()
    maven {
        url = uri("https://oss.sonatype.org/content/repositories/snapshots")
    }
}

// Module build.gradle

plugins {
    id("io.realm.kotlin")
}
kotlin {
    sourceSets {
        val commonMain  by getting {
            dependencies {
                implementation("io.realm.kotlin:library-base:<VERSION>-SNAPSHOT")
            }
        }
    }
}     

// Don't cache SNAPSHOT (changing) dependencies.
configurations.all {
    resolutionStrategy.cacheChangingModulesFor(0,TimeUnit.SECONDS)
}

See Config.kt for the latest version number.

Version Compatibility Matrix

With Kotlin Multiplatform still in Beta and the Compiler Plugin APIs being experimental, there might be restrictions on what versions of Kotlin the Realm Kotlin SDK supports. In the matrix below, you will find the minimum supported version for the dependencies of each Realm release.

Realm Version Requirements
1.10.0
  • Kotlin 1.8.0+
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.7.0+.
  • Gradle 6.8.3 - 7.6.1.
  • The new memory model only.
1.9.0
  • Kotlin 1.8.0+
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.8.3 - 7.6.1.
  • The new memory model only.
1.8.0
  • Kotlin 1.7.20+
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.7.1
  • Kotlin 1.7.20+
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.7.0
  • Kotlin 1.7.20 - 1.8.10
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.6.1
  • Kotlin 1.7.20+.
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.6.0
  • Kotlin 1.7.20 - 1.7.21.
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.5.2
  • Kotlin 1.7.20 - 1.7.21.
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.5.1
  • Kotlin 1.7.20 - 1.7.21.
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.5.0
  • Kotlin 1.7.20 - 1.7.21.
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.4.0
  • Kotlin 1.7.20 - 1.7.21.
  • AtomicFu 0.18.3+.
  • Ktor 2.1.2+.
  • Coroutines 1.6.4+.
  • Gradle 6.7.1 - 7.6.1.
  • The new memory model only.
1.3.0
  • Kotlin 1.6.10 - 1.7.10.
  • AtomicFu 0.17.0+.
  • Ktor 1.6.8.
  • Coroutines 1.6.0-native-mt.
  • Gradle 6.1.1 - 7.6.1.
1.2.0
  • Kotlin 1.6.10 - 1.7.10.
  • AtomicFu 0.17.0+.
  • Ktor 1.6.8.
  • Coroutines 1.6.0-native-mt.
  • Gradle 6.1.1 - 7.6.1.
1.1.0
  • Kotlin 1.6.10 - 1.7.10.
  • AtomicFu 0.17.0+.
  • Ktor 1.6.8.
  • Coroutines 1.6.0-native-mt.
  • Gradle 6.1.1 - 7.6.1.
1.0.2
  • Kotlin 1.6.10 - 1.7.10.
  • AtomicFu 0.17.0+.
  • Ktor 1.6.8.
  • Coroutines 1.6.0-native-mt.
  • Gradle 6.1.1 - 7.6.1.
1.0.1
  • Kotlin 1.6.10 - 1.7.10.
  • AtomicFu 0.17.0+.
  • Ktor 1.6.8.
  • Coroutines 1.6.0-native-mt.
  • Gradle 6.1.1 - 7.6.1.
1.0.0
  • Kotlin 1.6.10 - 1.7.10.
  • AtomicFu 0.17.0+.
  • Ktor 1.6.8.
  • Coroutines 1.6.0-native-mt.
  • Gradle 6.1.1 - 7.6.1.

While we strive to be compatible with other plugins and libraries like Android Gradle Plugin, Jetpack Compose and Compose Multiplatform, these plugins (and others) have their own version restrictions, so if you are running into build errors this would be the first thing to check:

You can find Kotlin version requirements for these libraries and plugins here:

Kotlin Memory Model and Coroutine compatibility

Realm Kotlin 1.3.0 and above only works with the new Kotlin Native memory model. This is also the default memory model from Kotlin 1.7.20 and onwards. This mean that you need the default Kotlin Coroutine library 1.6.0 and above and not the -mt variant, which have also been deprecated.

See the ## Compatibility section of the CHANGELOG for information about exactly which versions are compatible with a given version of Realm Kotlin.

When upgrading older projects, it is important to be aware that certain Gradle properties will control the memory model being used. So, if you have the Gradle properties below defined in your project. Make sure they are set to the values shown:

kotlin.native.binary.memoryModel=experimental
kotlin.native.binary.freezing=disabled

See https://kotlinlang.org/docs/native-memory-manager.html for more details about the new memory model.

Contributing

See CONTRIBUTING.md for more details!

Code of Conduct

This project adheres to the MongoDB Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to [email protected].

License

Realm Kotlin is published under the Apache 2.0 license.

This product is not being made available to any person located in Cuba, Iran, North Korea, Sudan, Syria or the Crimea region, or to any other person that is not eligible to receive the product under U.S. law.

More Repositories

1

SwiftLint

A tool to enforce Swift style and conventions.
Swift
18,607
star
2

realm-swift

Realm is a mobile database: a replacement for Core Data & SQLite
Objective-C
16,280
star
3

realm-java

Realm is a mobile database: a replacement for SQLite & ORMs
Java
11,451
star
4

jazzy

Soulful docs for Swift & Objective-C
Ruby
7,341
star
5

realm-js

Realm is a mobile database: an alternative to SQLite & key-value stores
TypeScript
5,758
star
6

realm-dotnet

Realm is a mobile database: a replacement for SQLite & ORMs
C#
1,243
star
7

realm-core

Core database component for the Realm Mobile Database SDKs
C++
1,016
star
8

realm-dart

Realm is a mobile database: a replacement for SQLite & ORMs.
Dart
758
star
9

SwiftCov

A tool to generate test code coverage information for Swift.
Swift
562
star
10

realm-browser-osx

DEPRECATED - Realm Browser for Mac OS X has been replaced by realm-studio which is cross platform.
Objective-C
501
star
11

realm-android-adapters

Adapters for combining Realm Java with Android UI components and framework classes
Java
414
star
12

realm-tasks

To Do app built with Realm, inspired by Clear for iOS
Swift
369
star
13

summer-of-swift

An ephemeral contest to learn Swift by doing
308
star
14

realm-studio

Realm Studio
TypeScript
300
star
15

realm-object-server

Tracking of issues related to the Realm Object Server and other general issues not related to the specific SDK's
Shell
293
star
16

RealmContent

Light Realm-powered content management system
Swift
238
star
17

realm-cocoa-converter

A library that provides the ability to import/export Realm files from a variety of data container formats.
Swift
219
star
18

realm-draw

The official Realm Draw app used in promotional videos
C#
163
star
19

github-gantt

Generate Gantt Charts From Github Issues!
JavaScript
156
star
20

realm-object-store

Cross-platform abstractions used within Realm products
C++
119
star
21

realm-kotlin-samples

Samples demonstrating the usage of Realm-Kotlin SDK
Kotlin
91
star
22

RChat

Swift
88
star
23

realm-graphql

GraphQL client for Realm Object Server
TypeScript
80
star
24

realm-loginkit

A generic interface for logging in to Realm Mobile Platform apps
Swift
74
star
25

realm-cpp

Realm C++
C++
73
star
26

realm-dart-samples

Samples for Realm Flutter and Realm Dart SDKs
C++
68
star
27

EventKit

A template conference app, featuring real-time schedule and data changes & running on Realm 🚀
Swift
63
star
28

realm-scanner

A scanning app that can analyze and report on any photos it is given
Java
54
star
29

react-realm-context

Components that simplifies using Realm with React
TypeScript
50
star
30

realm-graphql-service

GraphQL service for Realm Object Server
TypeScript
43
star
31

RealmPop

Java
39
star
32

my-first-realm-app

ToDo demo app using Realm and Realm Object Server to synchronize tasks.
Java
38
star
33

task-tracker-swiftui

Simple task manager using Realm and SwiftUI
Swift
36
star
34

realm-dvdrental

Demo inventory application which synchronizes data originating in Postgres via the Realm Postgres data connector.
Swift
36
star
35

realm-android-user-store

Java
35
star
36

realm-inventory

An sample inventory app demonstrating safe counters via Lists and Realm Counters
Swift
32
star
37

unity-examples

C#
30
star
38

realm-teamwork-MR

A Realm demo app showing an idealized version of a field-service type application using multiple Realms, permissions, etc
Swift
26
star
39

FindOurDevices

A React Native + MongoDB Realm application for allowing users to see location and movement of their own devices or those of people in the same private group.
JavaScript
25
star
40

node-template-project

A template for your Node and TypeScript Project with Visual Studio Code Debugging!
TypeScript
23
star
41

realm-flipper-plugin

A Flipper plugin to debug React Native applications using a Realm database.
TypeScript
20
star
42

realm-java-benchmarks

Kotlin
18
star
43

realm-drawkit

A modular drawing library that uses RMP for collaboration
Swift
17
star
44

aws-devicefarm

Github action for triggering runs on AWS devicefarm
JavaScript
17
star
45

Scrumdinger

Showing how the app from Apple's SwiftUI tutorial can be enhanced by adding Realm
Swift
16
star
46

awesome-realm

A curated list of awesome Realm resources, libraries, tools and applications
15
star
47

roc-ios

Swift
14
star
48

realm-search

An example implementation of synchronizing specific objects from a massive global Realm.
Swift
13
star
49

roc-ios-controller

A Chat Controller powered by Realm and Chatto
Swift
13
star
50

realm-puzzle

A small collaborative game where players work to complete a jigsaw puzzle.
Objective-C
12
star
51

realm-sync-demos

Demo apps for MongoDB Realm Sync
Kotlin
11
star
52

RCurrency

Swift
10
star
53

jazzy-integration-specs

Integration specs for https://github.com/realm/jazzy
HTML
10
star
54

realm-MultiUserTasksTutorial

Walk-though of constructing a multi-user example using Realm Tasks
Swift
9
star
55

charts

A Collection of Helm Charts
Smarty
9
star
56

realm-surveys

A reactive survey application powered by Realm
Swift
9
star
57

realm-connectors

Realm Object Server Data Connectors
8
star
58

realm-cloud-functions-demo

Realm & IBM Cloud Functions demo
JavaScript
8
star
59

realm-dotnet-groupedcollection

C#
8
star
60

realm-dotnet-lfs

C#
8
star
61

electron-react-samples

TypeScript
7
star
62

Realm-Sweeper

Swift
7
star
63

FindOurDevices-backend

A backend MongoDB Realm application for allowing users to see location and movement of their own devices or those of people in the same private group.
JavaScript
7
star
64

Realm-Drawing

Swift
6
star
65

feedback-manager

A simple Realm-powered feedback app that employs the Azure Text Analytics API to extract sentiment and key phrases from tickets
C#
5
star
66

BarCodes-Demo

A small demo app to show how to scan barcode and place into into a Realm
Swift
5
star
67

realm-qna

question and answer app
Swift
4
star
68

realm-dotnet-samples

C#
4
star
69

realm-swift-samples

Sample applications for realm-swift database
Swift
4
star
70

realm-tools

Various tools for testing Realm
TypeScript
3
star
71

ci-actions

A repository for commonly used GitHub Actions inside the various realm repositories
TypeScript
3
star
72

xamarin-examples-architecture

Test
C#
3
star
73

realm-flexible-sync-test-api

Sample App for A/B testing two version of the Flexible Sync API
Swift
3
star
74

realm-SharedTasks

Swift
2
star
75

unity-examples-3d-chess

Examples and tutorials for the Realm Unity SDK.
2
star
76

global-notifier-design-patterns

C++
2
star
77

realm.github.io

HTML
2
star
78

realm-object-server-cognito-auth

Cognito authentication provider for Realm Object Server
TypeScript
2
star
79

aws-devicefarm-sample-data

Sample data to use with the AWS devicefarm action
Java
1
star
80

realm-lua-bootcamp

Teaching the basics of building a Realm SDK
C++
1
star
81

realm-crowdcircle

A collaborative experimental game, played between 6 teams
Swift
1
star
82

realm-js-playground

JavaScript
1
star