2

In my application I'm using Realm Database to cache data. When application starts user can see cached data then application sends REST API Request to renew all data. In case if something was deleted I'm using this code:

val realm = Realm.getInstance(dbConfig)
    realm.beginTransaction()
    realm.apply {
        delete(SupportLineRealmModel::class.java)
        delete(ClientUserRealmModel::class.java)
        delete(ColleagueRealmModel::class.java)
        delete(ConferenceRealmModel::class.java)
        delete(ConferenceMemberRealmModel::class.java)
        delete(BusinessContactRealmModel::class.java)
        delete(AdvertisingSupportLineRealmModel::class.java)

        insertOrUpdate(supportLines)
        insertOrUpdate(clientUsers)
        insertOrUpdate(colleagues)
        insertOrUpdate(businessContacts)
        insertOrUpdate(adSupportLines)
        insertOrUpdate(conferences)
    }
    realm.commitTransaction()

But sometimes I get an Exception: Object is no longer valid to operate on. Was it deleted by another thread?. Looks like application is trying to get data from Realm in the middle of transaction.

When exactly RealmObject is deleted from Realm? After delete() or after commitTransaction() call? If after commitTransaction() Realm always should have all my objects, because REST API response always contains the same items.

Den
  • 1,284
  • 2
  • 14
  • 33
  • 1
    Well, you DID delete all the items, then you inserted new ones in their place. So yes, all currently obtained and existing objects WERE deleted on another thread. :P – EpicPandaForce Nov 30 '18 at 13:21
  • See the `EDIT:` here https://stackoverflow.com/a/39352718/2413303 to see a merging mechanism that doesn't involve the deletion of all existing objects. – EpicPandaForce Dec 01 '18 at 23:24

0 Answers0