Search code examples
javaandroidmultithreadingrealm

Wait for data update in realm-java between threads


I am having trouble with waiting for fresh data on a worker thread. The data object is copied to realm on a main thread, but almost immediately after that I need to access this object from a worker thread, which then reports that no such object exists in realm right now ( its newly opened realm instance ) . I remember that there was a method load() that would block execution to the point of next update, but it was removed in newer versions. And I can't use change notification for this as this is not a Looper thread..

The only way I can think of right now is to sleep the thread for some magic period of time and pray to god that it has updated already, but that approach is imho wildly indeterministic.

Can anybody advise here, how can I ensure that I read the most current data at the time ?


Solution

  • A possible hack would be to create a transaction that you cancel at the end.

    realm.beginTransaction(); // blocks while there are other transactions
    ... // you always see the latest version of the Realm here
    realm.cancelTransaction();
    

    This works if the thread is started after the UI thread saves the object into the Realm.

    You can also try this workaround: https://stackoverflow.com/a/38839808/2413303 (although it doesn't really help with waiting)