Realm object is not up to date

I have a singleton TimeManager that permanently listens to changes in my Session to perform backoffice stuff.

In the code below, I’m adding a TimeInterval object to the timeIntervals RealmList of my Session object after deleting the existing ones, each time a Session changes.

On a first change triggered by the UI, everything is fine and my Session has one TimeInterval object.

On a second change triggered by the UI, what’s going wrong is that nothing is deleted when I do session.timeIntervals.deleteAllFromRealm() as session.timeIntervals is empty, as the Timber log shows.

So it looks like the timeIntervals RealmList is not up to date, but calling realm.refresh() does not solve the issue. If I restart my app between the two changes, everything is fine.

I’ve tried to add an onSuccess listener just to see if it was called and it does. There is pretty much no lag as I’m doing this on an empty Realm.

Here is the code:

object TimeManager {

    private var sessions: RealmResults<Session>? = null

    private val sessionIdsToProcess = mutableSetOf<String>()

    init {

        val realm = Realm.getDefaultInstance()

        sessions = realm.where(Session::class.java).findAllAsync()
        sessions?.addChangeListener { _, _ ->

            if (sessionIdsToProcess.isNotEmpty()) {

                realm.executeTransactionAsync { asyncRealm ->

                    val sessions = sessionIdsToProcess.mapNotNull { asyncRealm.findById<Session>(it) }

                    for (session in sessions) {
                        Timber.d("TIME INTERVAL COUNT = ${session.timeIntervals.size}")
                        session.timeIntervals.deleteAllFromRealm()
                        val fti = TimeInterval()
                        session.timeIntervals.add(fti)
                        asyncRealm.insertOrUpdate(session)
                    }
                    sessionIdsToProcess.clear()
                }
            }
        }
        realm.close()
    }
}

How to make sure that session.timeIntervals is up to date?

I’ve created a github repository to make it easily testable:
https://github.com/laurentmorvillier/realmtest