VenomVendor
VenomVendor

Reputation: 15382

Realm Clone RealmQuery in different thread

How to clone RealmQuery in different thread?

Problem:

  1. Create RealmQuery in X Thread.
  2. Query for RealmResults is same thread.
  3. If Empty Results, get data from Server in Y Thread.
  4. Insert data to Realm in background thread (Y). <-- New Instance of realm
  5. Re-query with same filters as in 1 in Z Thread.
  6. Return results in Main Thread.

As of now, am getting java.lang.IllegalStateException: Realm accessed from incorrect thread.

Tried cloning using, RealmQuery.createQueryFromResult(RealmResults<E> queryResults). Internally the clone using the same realm instance of the results.

How would the clone behave if the queryResults was empty?

Would be better if clone can be done in RxJava2.

Upvotes: 2

Views: 250

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

Re-query with same filters as in 1 in Z Thread.

Return results in Main Thread.

Okay so this is completely unnecessary because you can create a RealmQuery and store a field reference to the RealmResults, add a RealmChangeListener to it, and when you insert into Realm on the background thread, it will automatically update the RealmResults and call the RealmChangeListener.

So you don't need to "re-query with same filters in Z thread" (because Realm's findAllSortedAsync() already queries on a background thread), and you don't need to manually return results in main thread because findAllSortedAsync() already does that.


Solution: use Realm's notification system (and async query API). Read the docs: https://realm.io/docs/java/latest/#notifications

Upvotes: 1

Related Questions