1. 程式人生 > >Take Realm to the next level with Kotlin

Take Realm to the next level with Kotlin

When someone asks me what I like the most about Kotlin, I find it hard to highlight a single feature.

Data classes, lambdas, type inference, delegates… all of which entail a complete series of significative improvements which makes the difference with respect to Java on a daily basis.

Discovering Kotlin extensions

Definitely, one of the features I use most is extensions. I take advantage of Kotlin extensions in all my Android projects.

The first time I heard about this concept was so strange. The possibility of adding functions to classes without inheriting from them, or even without having access to them, seemed useless and unnecessary to me.

What was the point of adding anything to classes out of my scope? My first impression was not very good. I thought it would lead to bad habits and a hard to understand code.

Nevertheless, all these doubts disappeared quickly when I started to comprehend all the power behind such a simple idea.

The ability to load an image from a url with something like imageView.loadFrom(url)

, to convert dp unit to px simply doing 10.toPx(context), or to remove a view from its parent with a method like view.removeFromParent() is just priceless. They are methods that I have always wanted to have.

Now I have the possibility of including them by myself so that they seem to really be part of the Android SDK.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

Realm meets Kotlin: there is strength in numbers

All of this has motivated me to write a small extensions library to simplify Realm usage.

If you have ever tried (and suffered) Realm for Android, you will know that it involves some boilerplate for common operations. Also, it has several constraints that complicate the work, like the need of opening and closing Realm instances manually and perform both operations in the same thread.

Another limitation is that you can’t pass your queries results between different threads if you don’t unlink them from Realm first. You have to pay attention to transaction management too, even if you want to perform a single operation.

There are examples of limitations that could be quite annoying and you have to be aware of them to avoid problems in the future.

My goal with this library is to turn Realm API into what I would have always liked it to be. I wanted to forget all Realm limitations and work on a higher abstraction layer.

The name of the library is Kotlin Realm Extensions, and you can find it on this link.

It is very simple to use. First, you must include the dependency into your build.gradle file:

123 compile'com.github.vicpinm:krealmextensions:1.0.4'

Secondly, you should know what this library is going to do for you:

  • Get the default Realm instance and close it when the transaction is finished.
  • Start and commit transactions
  • Unlink Realm objects in order to work with them in other threads.
  • Perform observable queries over the main thread (Realm requirement for this kind of queries)

Finally, we have to get down to work. Let’s see some examples:

Persist an entity with Java

123456789101112 User user=newUser("John");Realm realm=Realm.getDefaultInstance();try{realm.beginTransaction();realm.copyToRealmOrUpdate(user);realm.commitTransaction();}finally{realm.close();}

Equivalent with Kotlin Realm Extensions

123 User("John").save()

We also have available the saveAll() method for arrays and collections.

Query all entities for a given type with Java

123456789 Realm realm=Realm.getDefaultInstance();try{List events=realm.where(Event.class).findAll();events=realm.copyFromRealm(event);}finally{realm.close();}

Equivalent with Kotlin Realm Extensions

123 val events=Event().allItems

We can also perform conditional queries in a simple way:

123 val events=Event().query{it.equalTo("id",1)}

The lambda expression receives as parameter a RealmQuery instance with which we can link together our conditions to perform the query.

We can also perform our queries through observables and listen to data changes in real time. This could be quite tedious with Realm:

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

All this is reduced to something as simple as:

123 val obs=Event().allItemsAsObservable

Or if you want to constraint the query with conditions:

123 val obs=Event().queryAsObservable{it.equalTo("id",1)}

This is a small sample of the high degree of abstraction you can reach. Complete documentation is provided on the GitHub site.

Conclusion

As you can see, extensions usage can lead to greatly simplify our code in certain situations.

I still think that extensions should be used carefully and you should avoid abusing of them. But a good use of this feature can improve our code readability and maintainability and I think this library is a good sample of it.

I encourage you to try it and to leave your opinion.

Víctor is the developer of Kotlin Realm Extensions library. He’s Android & iOS Developer at DIGIO Soluciones Digitales

Shares

Like this:

Like Loading...

相關推薦

Take Realm to the next level with Kotlin

When someone asks me what I like the most about Kotlin, I find it hard to highlight a single feature. Data classes, lambdas, type inference, delegate

Taking a Product to the Next Level with Research and Planning

User Interviewing at the SF Union Square Apple StoreSince my user interview’s purpose was to get a closer look at an entire domain, I created a very brief

Go to the next level with GoLand 2018.2

Today we are happy to announce that GoLand 2018.2 is released! This major summer update has many goodies inside: support for Go modules out of

Tech Talk: How to Power Your Databases to the Next Level with AI

In this talk on databases powered by artificial intelligence, we will describe its design and implementation. Hint: we use unsupervis

Take a message to the next level

Take a message to the next levelVirtually in the shadow of Facebook, Mikael Yang has set up shop as founder of ManyChat. The company offers software that l

How Artificial Intelligence Will Go To the Next Level

Industry and academia have collaborated in artificial intelligence research for decades, but in recent years the power balance in this relationship has shi

Head of MIT-IBM Watson Research Lab on How AI Will Get to the Next Level

David Cox is director of the MIT-IBM Watson AI Lab, IBM Research By David Cox, Director, MIT-IBM Watson AI Lab Industry and academi

Anko to run background tasks with Kotlin in Android (KAD 09)

Anko is an Android library written in Kotlin by Jetbrains, that can be used for a lot of different stuff. Its main feature is to create views by code

Connect to the AWS Console with SAML

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Elon Musk promises system to link human brains with AI computers 'probably' within the next decade

Elon Musk believes humans must link up with machines in order to fight the inevitable onslaught of artificial intelligence. The SpaceX and Tesla CEO said h

question 002: dev c++ 當中如何調整字體大小?How to get the first program with C++? c++屬於什麽軟件?

space 什麽 pil get ctrl+鼠標 iostream 系統 using clu 方法:按住ctrl+鼠標滑輪滾動 c++屬於系統軟件還是應用軟件? 說哪個都不對,編譯之前屬於應用軟件,after compile ,it belongs to system so

翻譯(三)Stairway to T-SQL: Beyond The Basics Level 9: Dynamic T-SQL Code

數據庫表 studio 應用程序 cmd char 結束 管理 分代 應對 Stairway to T-SQL: Beyond The Basics Level 9: Dynamic T-SQL Code By Gregory Larsen, 2016/07/

the rs gold with up to $18 Vouchers to Vic Hati, S

rate mes europe escape layer graphic iot led oss Most Australians are not homophobic; consider the number runescape gold of homosexuals e

1.新建項目出現包名有一道紅線The SDK platform-tools version ((23)) is too old to check APIs compiled with API 20

新建 div 打開 platform 原因 check pla 分享 原因分析 原因分析: 就是platform-tools的版本太低導致的 解決方法: 1、點開SDK Manager,打開SDK Tools面板,將Platform-tools更新 2.更新完之後重啟a

Failed to load resource: the server responded with a status of 404 (Not Found)

PE nbsp ava col AI div short rtc not Failed to load resource: the server responded with a status of 404 (Not Found) 報錯情況:圖標加載失敗 原因分析:路徑錯誤

Use // eslint-disable-next-line to ignore the next line.解決辦法

npm start 啟動服務的時候,出現了一下報錯: You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* es

how do I access the EC Embedded Controller firmware level with wmi win32?

Imports System Imports System.Management Imports System.Windows.Forms Namespace WMISample Public Class MyWMIQuery Public Overloads Shar

How to Add “Open with Notepad” to the Windows Context Menu for All Files

If you want to open a file type not registered with Notepad, you have to click through several options to make it happen. This can be a hassle, so

VUE vue——解決“You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ t

vue——解決“You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ to ignore

小程式執行報錯:“Failed to load local image resource xxx.png the server responded with?

錯誤原因: 由於這是因為初始化的時候,變數還沒渲染進去導致的。 解決方法: 在src前面加個: wx:if<image wx:if='{{customerLevel.value}}' class