I've read the warnings about keeping long-lived Realm
instances on background non-Looper threads. I've also seen the suggestion that opening and closing Realm
instances quickly is not the best idea. Given those constraints (if either is invalid, let me know), I'm trying to identify the best way to use Realm with websockets, where websocket events contain information that requires access to the Realm
.
Particularly, what is the right way to go between these options (or something else entirely?):
- Open and close the
Realm
on every event - Open the
Realm
at the start of the thread, periodically (every 30s or so) begin and commit transaction on the thread to bring the Realm up to date. - Allocate a
Looper
for the thread that handles websocket messages. Create theRealm
instance once on the thread, and leave it open for the thread's lifetime, using theLooper
to keep it up to date.
Other things worth noting:
- The client will already have a
Realm
open on the UI thread. So, as far as I understand, this means the background threads at least do not need to pay the price of schema validation. - There's no way to predict the frequency of websocket events. In the typical case, there may be no more than one or two events per second. However, in the case that a large operation happens on the server which changes a bunch of objects, the client may receive hundreds or thousands of websocket events fairly rapidly.