After upgrading from 0.80.1 to 0.80.3, refresh() and the change listeners stop working. They work once or twice, but then stop refreshing or getting new changes.
Hi @FaisalAbid
We made a change in 0.80.3 so that ChangeListeners are weak references inside Realm. This was due to fix other potential memory leaks, but it also means that if you do something like this:
realm.addChangeListener(new RealmChangeListener() {
...
});
your ChangeListener risk getting garbage collected which would give the error you see. If you save the listener in a field variable it should work:
public class MyActivity extends Activity {
private RealmChangeListener listener = new RealmChangeListener() {
..
};
protected onCreate() {
Realm realm = Realm.getInstance(this);
realm.addChangeListener(listener);
}
...
}
We could probably have documented that change better.
Cool thanks, this works once made into a field
You might want to mention it somewhere in the documentation on this page. I had the same problem with an object change listener and for the life of me couldn't figure out what I was doing wrong until I found this issue.
Ditto on mentioning this in the documentation. I too wasted a day trying to get this to work, and even tried the trick mentioned here, when finally I realized that I was closing the last reference to the realm instance which prevented the change listener from ever being called.
The example in the documentation (https://realm.io/docs/java/latest/#notifications) does it as outlined above. But we could add a short note in the text about weak references.
With this code my app worked easily. But since listening to the socket in the IntentServiceand updating the database there, the RealmChangeListener sometimes works and sometimes not... why?
You need to keep a strong reference to the RealmResults. ¯\_(ツ)_/¯
We recently updated https://realm.io/docs/java/latest/#notifications with a few examples that hopefully make this more clear
Most helpful comment
Hi @FaisalAbid
We made a change in 0.80.3 so that ChangeListeners are weak references inside Realm. This was due to fix other potential memory leaks, but it also means that if you do something like this:
your ChangeListener risk getting garbage collected which would give the error you see. If you save the listener in a field variable it should work:
We could probably have documented that change better.