Kotlin Realm Extensions


Source link: https://github.com/vicpinm/Kotlin-Realm-Extensions

Kotlin extensions to simplify Realm API.

Description

Simplify your code to its minimum expression with this set of Kotlin extensions for Realm. Forget all boilerplate related with Realm API and perform database operations in one line of code with this lightweight library. Full test coverage.

Download for Kotlin 1.1.x and Realm 4.1.x

Grab via Gradle:

repositories {

  mavenCentral() 
}
  compile "com.github.vicpinm:krealmextensions:2.0.0-beta1"  //For Single and Flowable queries: compile 'io.reactivex.rxjava2:rxjava:2.1.4' compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

Download for Kotlin 1.1.x and Realm 3.5.0

Grab via Gradle:

repositories {

  mavenCentral() 
}
  compile "com.github.vicpinm:krealmextensions:1.2.0"  //For Observable queries: compile 'com.github.vicpinm:krealmextensions-rxjava:1.2.0'  //For Single and Flowable queries: compile 'com.github.vicpinm:krealmextensions-rxjava2:1.2.0'

Download for Kotlin 1.1.x and Realm 3.1.3

Grab via Gradle:

repositories {

  mavenCentral() 
}
  compile 'com.github.vicpinm:krealmextensions:1.0.9'

Download for Kotlin 1.0.x and Realm 2.2.1

Grab via Gradle:

repositories {

  mavenCentral() 
}
  compile 'com.github.vicpinm:krealmextensions:1.0.6'

Features

Forget about:

  • Realm instances management
  • Transactions
  • Threads limitations
  • Boilerplate related with Realm API

Usage

All methods below use Realm default configuration. You can use different Realm configurations per model with RealmConfigStore.init(Entity::class.java, myConfiguration). See application class from sample for details. Thanks to @magillus for its PR.

Store entities

All your entities should extend RealmObject.

Before (java)

User user = new User("John");
  Realm realm = Realm.getDefaultInstance();
 try{

 realm.executeTransaction(realm -> {

 realm.copyToRealmOrUpdate(user);

}
);

}
 finally {

 realm.close();
 
}

After (Kotlin + extensions)

User("John").save()

Save method creates or updates your entity into database. You can also use create() method, which only create a new entity into database. If a previous one exists with the same primary key, it will throw an exception.

Save list: Before (java)

List<User> users = new ArrayList<User>(...);
  Realm realm = Realm.getDefaultInstance();
 try {

  realm.executeTransaction(realm -> {

realm.copyToRealmOrUpdate(users);

 
}
);
 
}
 finally {

  realm.close();
 
}

Save list: After (Kotlin + extensions)

listOf<User>(...).saveAll()

If you need to provide your own Realm instance, you can use the saveManaged(Realm) and saveAllManaged(Realm) methods. These methods return managed objects. You should close manually your Realm instance when you finish with them.

Query entities

All query extensions return detached realm objects, using copyFromRealm() method.

Get first entity: Before (java)

Realm realm = Realm.getDefaultInstance();
 try {

 Event firstEvent = realm.where(Event.class).findFirst();

 firstEvent = realm.copyFromRealm(event);
 
}
 finally {

 realm.close();
 
}

Get first entity: After (Kotlin + extensions)

val firstEvent = Event().queryFirst()

You can use lastItem extension too.

Get all entities: Before (java)

Realm realm = Realm.getDefaultInstance();
 try {

  List<Event> events = realm.where(Event.class).findAll();

  events = realm.copyFromRealm(event);
 
}
 finally {

  realm.close();
 
}

Get all entities: After (Kotlin + extensions)

val events = Event().queryAll()

Get entities with conditions: Before (java)

Realm realm = Realm.getDefaultInstance();
 try{

  List<Event> events = realm.where(Event.class).equalTo("id",1).findAll();

  events = realm.copyFromRealm(event);
 
}
 finally {

  realm.close();
 
}

Get entities with conditions: After (Kotlin + extensions)

val events = Event().query {
 query -> query.equalTo("id",1) 
}
 //NOTE: If you have a compilation problems in equalTo method (overload ambiguity error), you can use equalToValue("id",1) instead

If you only need the first or last result, you can also use:

val first = Event().queryFirst {
 query -> query.equalTo("id",1) 
}
 val last = Event().queryLast {
 query -> query.equalTo("id",1) 
}

Get sorted entities

val sortedEvents = Event().querySorted("name",Sort.DESCENDING) 
val sortedEvents = Event().querySorted("name",Sort.DESCENDING) {
 query -> query.equalTo("id",1) 
}

Delete entities

Delete all: Before (java)

Realm realm = Realm.getDefaultInstance();
 try{

  List<Event> events = realm.where(Event.class).findAll();

  realm.executeTransaction(realm -> {

events.deleteAllFromRealm();

  
}
);
 
}
 finally {

  realm.close();
 
}

Delete all: After (Kotlin + extensions)

Event().deleteAll()

Delete with condition: Before (java)

Realm realm = Realm.getDefaultInstance();
 try{

  List<Event> events = realm.where(Event.class).equalTo("id",1).findAll().deleteAllFromRealm();

  events = realm.copyFromRealm(event);
 
}
 finally {

  realm.close();
 
}

Delete with condition: After (Kotlin + extensions)

Event().delete {
 query -> query.equalTo("id", 1) 
}

Observe data changes

Before (java)

Realm realm = Realm.getDefaultInstance();
 Flowable<List<Event>> obs =  realm.where(Event.class).findAllAsync() .asFlowable() .filter(RealmResults::isLoaded) .map(realm::copyFromRealm) .doOnUnsubscribe(() -> realm.close());

After (Kotlin + extensions)

val obs = Event().queryAllAsFlowable()

Observe query with condition: Before (java)

Realm realm = Realm.getDefaultInstance();
 Flowable<List<Event>> obs =  realm.where(Event.class).equalTo("id",1).findAllAsync() .asFlowable() .filter(RealmResults::isLoaded) .map(realm::copyFromRealm) .doOnUnsubscribe(() -> realm.close());

Observe query with condition: After (Kotlin + extensions)

val obs = Event().queryAsFlowable {
 query -> query.equalTo("id",1) 
}

These kind of observable queries have to be performed on a thread with a looper attached to it. If you perform an observable query on the main thread, it will run on this thread. If you perform the query on a background thread, a new thread with a looper attached will be created for you to perform the query. This thread will be listen for data changes and it will terminate when you call unsubscribe() on your subscription.

RxJava 2 Single support (thanks to @SergiyKorotun)

val single = Event().queryAllAsSingle() val single = Event().queryAsSingle {
 query -> query.equalTo("id", 1) 
}
 

Proguard

You need to add these rules if you use proguard, for rxjava and realm:

# rxjava -dontwarn sun.misc.**  -keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {

 long producerIndex;
 long consumerIndex; 
}
  -keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {

  rx.internal.util.atomic.LinkedQueueNode producerNode; 
}
  -keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {

  rx.internal.util.atomic.LinkedQueueNode consumerNode; 
}
  -dontnote rx.internal.util.PlatformDependent  -keepnames public class * extends io.realm.RealmObject -keep class io.realm.annotations.RealmModule -keep @io.realm.annotations.RealmModule class * -keep class io.realm.internal.Keep -keep @io.realm.internal.Keep class * -dontwarn io.realm.**

Resources

A different beautiful Floating Edit Text.

JsonAnnotation can speed up Android development. It generates gson model class by json string automatically and lets you concentrate on what's really important.

The library allows to create fixed collage (cards can not be moved, scaled or rotated) or dynamic collage (cards can move, scale and rotate).

CustomMenu is a custom control that can help you to create Menu quickly.

Transform images into pixel versions of itself in Android.

Simple and effective bug reporting tool for Android apps.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes