GithubHelp home page GithubHelp logo

husseinhj / realm-kotlin Goto Github PK

View Code? Open in Web Editor NEW

This project forked from realm/realm-kotlin

0.0 0.0 0.0 5.73 MB

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

License: Apache License 2.0

Shell 0.68% Ruby 0.05% C++ 3.23% C 0.12% Kotlin 95.19% CMake 0.09% Dockerfile 0.04% SWIG 0.60%

realm-kotlin's Introduction

Realm

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.
  • 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 that includes a cloud backend and Sync.

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:

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.

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.

realm-kotlin's People

Contributors

cmelchior avatar rorbech avatar clementetb avatar nhachicha avatar edualonso avatar bmunkholm avatar elle-j avatar jacoboscargunnarsson avatar nathan-contino-mongo avatar lapeste avatar ianpward avatar gagik avatar finnschiermer avatar konnovdev avatar nielsenko avatar kneth avatar tonnyl avatar geragray avatar astatio avatar ellullo avatar seanadams540 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.