Coder Social home page Coder Social logo

arunkumar9t2 / compass Goto Github PK

View Code? Open in Web Editor NEW
18.0 3.0 1.0 3.52 MB

🧭 Collection of Kotlin APIs/tools to make using Realm Mobile database easier

Home Page: https://arunkumar9t2.github.io/compass

License: Apache License 2.0

Kotlin 98.41% Dockerfile 1.59%
realm android mongodb-realm jetpack-paging jetpack realm-java realm-mobile-database

compass's Introduction

Compass

Kotlin API and tools to make working with Realm easier

Components

Compass is designed to make working with Realm easier through collection of Kotlin types and extensions that handle Realm's lifecycle and threading model effectively. It has two major components

  • compass - The core Kotlin API with set of extensions for common patterns around Realm's lifecycle and threading.
  • compass-paging - Provides extensions to integrate with Jetpack Paging 3.
  • more coming soon..™

Getting Started

Compass is available as android library artifacts on mavenCentral. In root build.gradle:

allprojects {
  repositories {
    mavenCentral()
  }
}

Or in dependenciesResolutionManagement in settings.gradle:

dependencyResolutionManagement {
  repositories {
    mavenCentral()
  }
}

Then in your modules:

dependencies {
    implementation "dev.arunkumar.compass:compass:1.0.0"
    // Paging integration
    implementation "dev.arunkumar.compass:compass-paging:1.0.0"
}

Setup

Compass assumes Realm.init(this) and Realm.setDefaultConfiguration(config) is called already and acquires a default instance of Realm using Realm.getDefaultInstance() where needed.

Features

Query construction

Use RealmQuery construction function to build RealmQuery instances. Through use of lambdas, RealmQuery{} overcomes threading limitations by deferring invocation to usage site rather than call site.

val personQueryBuilder =  RealmQuery { where<Person>().sort(Person.NAME) }

Extensions like getAll() is provided on RealmQueryBuilder that takes advantage of this pattern.

Threading

Realm's live updating object model mandates few threading rules. Those rules are:

  1. Realms can be accessed only from the thread they were originally created
  2. Realms can be observed only from threads which have Android's Looper prepared on them.
  3. Managed RealmResults can't be passed around the threads.

Compass tries to make it easier to work with Realm by providing safe defaults.

RealmExecutor/RealmDispatcher

RealmExecutor and RealmDispatcher are provided which internally prepares Android Looper by using HandlerThreads. The following is valid:

withContext(RealmDispatcher()) {
    Realm { realm -> // Acquire default Realm with `Realm {}`
        val persons = realm.where<Person>().findAll()

        val realmChangeListener = RealmChangeListener<RealmResults<Person>> {
            println("Change listener called")
        }
        persons.addChangeListener(realmChangeListener) // Safe to add

        // Make a transaction
        realm.transact { // this: Realm
            copyToRealm(Person())
        }
        
        delay(500)  // Wait till change listener is triggered
    } // Acquired Realm automatically closed
}

Note that RealmDispatcher should be closed when no longer used to release resources. For automatic lifecycle handling via Flow, see below.

Streams via Flow

Compass provides extensions for easy conversions of queries to Flow and confirms to basic threading expectations of a Flow

  • Returned objects can be passed to different threads.
  • Handles Realm lifecycle until Flow collection is stopped.
val personsFlow = RealmQuery { where<Person>() }.asFlow()

Internally asFlow creates a dedicated RealmDispatcher to run the queries and observe changes. The created dispatcher is automatically closed and recreated when collection stops/restarted. By default, all RealmResults objects are copied using Realm.copyFromRealm.

Read subset of data.

Copying large objects from Realm can be expensive in terms of memory, to read only subset of results to memory use asFlow() overload that takes a transform function.

data class PersonName(val name: String)

val personNames = RealmQuery { where<Person>() }.asFlow { PersonName(it.name) }

Paging

Compass provides extensions on RealmQueryBuilder to enable paging support. For example:

val pagedPersons = RealmQuery { where<Person>() }.asPagingItems()

asPagingItems internally manages a Realm instance, run queries using RealmDispatcher and cleans up resources when Flow collection is stopped.

For reading only subset of objects into memory, use the asPagingItems() overload with a transform function:

val pagedPersonNames = RealmQuery { where<Person>() }.asPagingItems { it.name }
ViewModel

For integration with ViewModel

class MyViewModel: ViewModel() {

    val results = RealmQuery { where<Task>() }.asPagingItems().cachedIn(viewModelScope)
}

The Flow returned by asPagingItems() can be safely used for transformations, separators and caching. Although supported, for converting to UI model prefer using asPagingItems { /* convert */ } as it is more efficient.

Compose

The Flow<PagingData<T>> produced by asPagingItems() can be consumed by Compose with collectAsLazyPagingItems() from paging-compose:

val items = tasks.collectAsLazyPagingItems()
  LazyColumn(
    modifier = modifier.padding(contentPadding),
  ) {
    items(
      items = items,
      key = { task -> task.id.toString() }
    ) { task -> taskContent(task) }
  }

FAQ

Why not Realm Freeze?

Frozen Realm objects is the official way to safely move objects around threads. However it still says connected to underlying Realm and poses risk around threading.

Frozen objects remain valid for as long as the realm that spawned them stays open. Avoid closing realms that contain frozen objects until all threads are done working with those frozen objects.

Compass's transform API supports both creating detached objects from Realm and reading subset of Realm object into memory.

For detailed comparison, see here.

Resources

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.