Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Realm ChangeListener not being triggered

Tags:

android

realm

I've got a Realm results change listener that isn't being triggered, here's the code:

final RealmResults<LogEntry> entries = realm.where(LogEntry.class).findAll();

entries.addChangeListener(new RealmChangeListener<RealmResults<LogEntry>>() {
            @Override
            public void onChange(RealmResults<LogEntry> results) {
                Log.v("Testing", "The size is: " + results.size());
            }
        });

There is definitely new stuff being added, I have a log on the realm insertion printing out the new size of the table, yet for some reason the change listener does nothing? Am I missing something here, it seems identical to the docs.

like image 380
Carling Knight Avatar asked Apr 02 '17 23:04

Carling Knight


1 Answers

You need to keep a class reference to entries to prevent it from being GC'ed:

public MyClass {

  private RealmResults<LogEntry> entries;

  public void myMethod() {

    entries = realm.where(LogEntry.class).findAll();
    entries.addChangeListener(new RealmChangeListener<RealmResults<LogEntry>>() {
            @Override
            public void onChange(RealmResults<LogEntry> results) {
                Log.v("Testing", "The size is: " + results.size());
            }
        });
    }
}
like image 67
Christian Melchior Avatar answered Oct 13 '22 00:10

Christian Melchior