Realm observer not removed

Martin Mlostek Source

I am using a small helper class like this

class RealmWatcher<T>(private val query: RealmResults<T>,
                      private val handler: (RealmResults<T>) -> Unit,
                      private val logger: Logger? = null) {

    private val handlerWrapper: (RealmResults<T>) -> Unit = { result ->
        logger?.trace("⟳  '$result")
        handler.invoke(query)
    }

    fun start() {
        stop()
        handler.invoke(query)
        query.addChangeListener(handlerWrapper) 
    }

    fun stop() {
        query.removeChangeListener(handlerWrapper)
    }
}

to start and stop the listeners in my fragments in onResume and `onPause``

Now I am seeing that those observers are note removed correctly. I have gone deep into Realm and see those lines in OsResults

public <T> void removeListener(T observer, RealmChangeListener<T> listener) {
    removeListener(observer, new RealmChangeListenerWrapper<T>(listener));
}

Which leads me to my assumption that there is a bug inside realm. Because a new RealmChangeListenerWrapper wrapper is created, and the

    public boolean equals(Object obj) {
        return obj instanceof RealmChangeListenerWrapper &&
                listener == ((RealmChangeListenerWrapper) obj).listener;
    }

fails because its a different listener, and thus won't be removed.

Am I doing something wrong or is this a realm bug?

androidrealmrealm-mobile-platform

Answers

answered 3 months ago EpicPandaForce #1

public boolean equals(Object obj) {
    return obj instanceof RealmChangeListenerWrapper &&
            listener == ((RealmChangeListenerWrapper) obj).listener;
}

Both addListener and removeListener create a RealmChangeListenerWrapper, so that's definitely true.

It verifies that listener is the same instance as the other listener, so that should work too if you're removing the same listener you registered previously.

So assuming you call

realmWatcher.start()
// change listener should be added
realmWatcher.stop()
// change listener should be removed

Then the observer should be removed properly from the RealmResults, because handlerWrapper is the same instance both times.

If that doesn't happen, I'd appreciate a sample github project that reproduces this.

comments powered by Disqus