Observing Realm as Kotlin Flows

I’m warking on an Android app using Realm, and I want to actively observe the data I have on the Realm DB through Kotlin Flows. I have been doing that like this:

val myListFlow = Realm.getDefaultInstance()
    .where(MyRealmModel::class.java)
    .findAllAsync()
    .toFlow()
    .filter {it.isValid}
    .flowOn(Dispatchers.Main)
    .map { 
        it.toList()
     }
    .flowOn(Dispatchers.IO)

However, I’m seeing more often crashes related to “Cannot modify managed objects outside of a write transaction.” – is there any way to prevent that? should I be freezing these objects or doing something else?

Thanks in advance,

The error states that you are modifying an object outside of a write transaction.

Please check what are you doing with the myListFlow objects, it contains managed objects that can only be modified within a transaction.

Thanks! Is there a way to make sure I completely unhook the objects from Realm so I don’t run into these issues. I started doing a:

.map { realm.copyFromRealm(it) } 

and I think it might have got rid of the issue, but IDK if it is enough, is there something else that I should be doing? should I also make sure that the object is managed before doing the copy?

.filter { it.isValid && it.isManaged }.map { realm.copyFromRealm(it) } 

Thanks a lot for your help!

copyFromRealm would help avoid the issue, it creates a copy of the data, so any further modifications would not be persisted thus not require to be within a transaction.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.