realm-java: RealmChangeListener on empty RealmResults never fires

Goal

Receive change updates on a RealmQuery

Expected Results

When the RealmQuery changes, the RealmChangeListener is fired

Actual Results

The RealmChangeListener is never fired

Steps & Code to Reproduce

I create a query (realm.where(Test.class).findAll()), and add a RealmChangeListener to the returned RealmResults (I maintain a strong reference to the RealmResults).

If the query was empty when I made it, the RealmChangeListener never fires, no matter how many times I insert an object that matches the query after that. If there is an object when the query is made, the the RealmChangeListener does fire, even if all the objects are removed and then another one is inserted.

Version of Realm and tooling

Realm version(s): 3.3.1

Realm sync feature enabled: no

Android Studio version: 3.0 Canary 3

Which Android version and device: Pixel 7.1.2

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 25 (13 by maintainers)

Most upvoted comments

See https://realm.io/docs/java/latest/api/io/realm/RealmResults.html

Adds a change listener to this RealmResults. Registering a change listener will not prevent the underlying RealmResults from being garbage collected. If the RealmResults is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

 public class MyActivity extends Activity {

     private RealmResults<Person> results; // Strong reference to keep listeners alive

     @Override
     protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       results = realm.where(Person.class).findAllAsync();
       results.addChangeListener(new RealmChangeListener<RealmResults<Person>>() {
           @Override
           public void onChange(RealmResults<Person> persons) {
               // React to change
           }
       });
     }
 }

On top of that, you’re calling copyFromRealm instead of, like, copyToRealmOrUpdate or insertOrUpdate or anything that actually writes into the db. Also, running synchronous transaction inside a change listener?

Are you trying to get an infinite loop? 😕

What are you doing???

@kneth sorry I haven’t got a chance to try. Crazy sprints at work.

@beeender I haven’t been able to set aside time for it yet.

Deletion is fine. I just want to make sure other objects aren’t added.

I changed my process to copy from the RealmResults, and do an in query later to delete them. Less performant, but it works.

I’ll have to revisit later, but I believe that the filter on non empty (this time on the unmanaged list) still caused the issue where the RealmChangeListener wouldn’t fire. At this point not sure if it’s a realm issue, an rx issue, or both. I’ll update when I make a sample project.