How to add a new element to RealmList inside a write transaction? (Kotlin SDK)

46 Views Asked by At

The documentation says that we can add new elements to a RealmList, but this code doesn't work:

class AppSettings : RealmObject {
    @PrimaryKey
    var id: String = "uuid"
    var isFirstLaunch: Boolean = false
    var colorPresets: RealmList<String> = realmListOf()
}

realm.writeBlocking {
    val appSettings = realm.query<AppSettings>().first().find() ?: return@writeBlocking
    appSettings.colorPresets.add(hexCode)
}

I get the following error - "Cannot modify managed List outside of a write transaction."

What does it mean? The append operation occurs within a write transaction. What am I doing wrong?

1

There are 1 best solutions below

0
San On

I realized what I was doing wrong. My mistake was that I specified not "this.query()", but "realm.query()" (inside a write transaction).

This is how it should be:

realm.writeBlocking {
    val appSettings = this.query<AppSettings>().first().find() ?: return@writeBlocking
    appSettings.colorPresets.add(hexCode)
}