Realm Kotlin Tutorial

First things first, make sure you followed the official Realm tutorial on how to install it on your Android project.

Here’s how I implemented it on my Android project using Kotlin. After installation, initialize the Realm instance on your Application class or your launcher Activity.

import io.realm.Realm
class MyApplication : Application() {
    override fun onCreate() {

Create your Realm object by extending the RealmObject class.

import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Message(
    @PrimaryKey var id: String = "",
    var firstName: String = "",
    var lastName: String = "",
    var email: String = "",
    var password: String = ""
) : RealmObject()

Let’s create our Singleton class where we will encapsulate our Realm configuration and instance.

import io.realm.Realm
import io.realm.RealmConfiguration
object AppDatabase {
    var realmInstance: Realm
    init {
        val realmConfiguration = RealmConfiguration.Builder()
        realmInstance = Realm.getInstance(realmConfiguration)

Take note I declared AppDatabase as a Kotlin Object and not a class. Kotlin Objects are handy for one time use classes or singletons.

Another thing to take notice of is the method allowWritesOnUiThread(), Realm will throw an Exception if you will write or read Realm objects inside Coroutines.

Now, let’s say we will retrieve data from the API and then save it in our Realm database. Here’s how I implemented it.

CoroutineScope(Dispatchers.IO).launch {
    // Get data from API
    withContext(Dispatchers.Main) {
          AppDatabase.realmInstance.executeTransaction {

And if we want to retrieve data from Realm

val messageList = AppDatabase.realmInstance.where(

Let me know if you have any questions by commenting below.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

  You are commenting using your account. Log Out /  Change )

Twitter picture

  You are commenting using your Twitter account. Log Out /  Change )

  You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s