Realm data sync not consistent

后端 未结 1 1480
夕颜
夕颜 2021-01-25 13:57

I am having an issue where Realm sometimes returns me different data every time I do the same query. Currently I am using an SyncAdapter for uploading. The idea is that we are t

相关标签:
1条回答
  • 2021-01-25 14:19

    After some researching I found out what was the problem. But please correct me if I'm wrong. I replaced my Subscribers.io() with Subscribers.newThread() in my Rx calls and now it works fine. So my theory is:

    Before calling my UploadAdapter to upload the changed data I am using an Rx call with Subscribers.io() to insert my item in the database. Subscribers.io() uses a threadpool to reuse threads, or creates new threads if neccessary. So let's say it spawns a thread called "A". Thread A get's a Realm instance (let's say that Realm snapshot is "1") and inserts into it the created item. After that SyncAdapter get's called and it also get's a new Realm instance with the same Realm snapshot "1". After SyncAdapter finishes uploading data to the server it deletes the old item, and insert the new item it got from the server. So after this Realm data changed so the newest Realm snapshot is now "2". SyncAdapter sends a broadcast to the Activity that the upload is finished and it should get the new data from the Realm database.

    For reading data from Realm I am also using Rx with Subscribers.io(). So when requesting new data from Realm the Subscribers.io() has already a thread in it's pool that is waiting to be reused, and that's thread "A". And since this thread is a non Looper thread it doesn't know that Realm data changed and it still uses the Realm snapshot "1", so that's why I get old data from Realm. And after refreshing a few times Subscribers.io() probably creates a new thread, let's say thread "B".

    So thread "B" also get's a Realm snaphot, and this time it is the newest snapshot, so snapshot "2". And it returns the correct data.

    So when using Subscribers.newThread() it always creates a new thread and it always has the newest Realm snapshot.

    Here is a link regarding the difference between Subscribers.io() and Subscribers.newThread(): Retrofit with Rxjava Schedulers.newThread() vs Schedulers.io()

    Hope this helps someone!

    0 讨论(0)
提交回复
热议问题