Precautions for updating Realm object

Introduction

When developing an Android app, when trying to update data using Realm,

Cannot modify managed objects outside of a write transaction. Error was output.

why?

Error summary

The database has been updated outside the transaction.

...
DB update process
...

realm.beginTransaction()
realm.copyToRealmOrUpdate(DB)
realm.commitTransaction()

What is a transaction?

Simply put Multiple processes that require consistency of results.

So what is the cause of the error?

When a transaction is separated, it becomes inconsistent and the transaction fails even though the transaction needs to be successful.

solution

Perform update processing within a transaction.

Concrete example

realm.beginTransaction()

...
DB update process
...

realm.copyToRealmOrUpdate(DB)
realm.commitTransaction()

reference

What is a "transaction"? I tried to talk about it in a super easy way!

Recommended Posts

Precautions for updating Realm object
[Java] Precautions for type conversion
[ruby + excel] Precautions for Save As