Reputation: 6737
Is it ok to write to Realm on the main thread?
Basically I'd like to write some ObjectA
to Realm right before starting ActivityA
.
Once ActivityA
starts it needs immediate access (in onCreate
) to ObjectA
- can I also read on the main thread?
Basically this ObjectA
is too large to pass through the bundle so I need to store it in a cache.
I was initially thinking of storing the object in an in-mem cache and then storing it in Realm after the activity starts, but was wondering if I could skip having to write my own in-mem cache.
Upvotes: 3
Views: 3084
Reputation: 1
In general it's bad practice to do anything other than UI on main thread.
We have an app doing as explained in other answers (writing on background thread, reading on UI thread) and it's causing lots of ANRs. On high-end devices it's nearly not noticeable, however on low end devices it takes frequent ANRs (in seconds) constantly.
For that reason, we are removing any DB loading we have in onCreate and recommend anyone doing so as well.
It's best to have the UI shows a loading message/icon than have the whole activity dead for several seconds.
Upvotes: 0
Reputation: 81539
Is it ok to write to Realm on the main thread?
Writing to Realm on the UI thread has two implications:
1.) any RealmResults created by asynchronous query api will be evaluated immediately and synchronously on UI thread when the transaction is opened
2.) if a background thread is already writing to Realm in a transaction, then it will block UI thread until that transaction is committed.
In your use-case, you seem to rely on Realm for immediate caching on the UI thread for a single object, so you can write (without getting blocked), and you need the single object immediately (so you need findFirst()
which is synchronous API).
So in your case it's most likely safe to use Realm on UI thread.
In general, the Realm best practice is to write to Realm on background thread, and read from Realm on UI thread (by keeping field reference to RealmResults, adding a RealmChangeListener to it, and then receiving the updated results on each change made to Realm).
Upvotes: 3