0

In my test I have the following code:

/* two users written to realm here, verified */

TestSubscriber<RealmResults<User>> testSubscriber = new TestSubscriber<>();

usersByQuery(getRealm().where(User.class))
    .filter(RealmResults::isLoaded)
    .subscribe(testSubscriber);

    /*
       .subscribe(users1 -> {
        assertTrue("Users are not two, found instead: " + users1.size(), users1.size() == 2);
        Log.d("Another test", "" + users1.size() + " users on thread: " + Thread.currentThread().getName());
    }); 
   */

   try {
        Log.d("Test", "Sleeping on " + Thread.currentThread().getName() + "\n");
        Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
    }

    testSubscriber.assertValueCount(1);

The test will fail with:

java.lang.AssertionError: Number of onNext events differ; expected: 1, actual: 0

If I replace the testSubscriber with the commented subscribe and remove the test subscriber assertion, it will pass and output:

D/Test: Sleeping on mainD/Another test: 2 users on thread: main

I do not understand why the TestSubscribers OnNext will not be called when the other one will. I'd like to use the test subscriber so I can replace the Thread.sleep block with an awaitValueCount.

ferbeb
  • 163
  • 1
  • 2
  • 11
  • Your Realm instance doesn't get auto-updated because it is not on a looper thread. You can force a refresh with the answer on http://stackoverflow.com/questions/38833163/realmchangelistener-does-not-get-called-when-realm-gets-updated-in-notificationl although that forces synchronous execution of your async query. Another possibility is using a scheduler that has a looper. – EpicPandaForce Oct 25 '16 at 15:18
  • @EpicPandaForce I fixed that by using `InstrumentationRegistry.getInstrumentation().runOnMainSync`, I think it throws an Exception if you do not ensure Realm is on a Looper thread. Also, that would not explain the difference in the behaviour of the TestSuscriber compared to the normal subscribe, or would it? – ferbeb Oct 27 '16 at 06:29

0 Answers0