I'm performing some investigation of Realm
threading and encountered issue.
In this simple example I have 2 Thread
objects, one for writing and second one for reading. The reader Thread
gets count of written objects always as 0, but inside writer scope the size()
for items in DB is correct. When I relaunch app, the reader gets the first count ok before any insertions.
Thread writer = new Thread() {
@Override
public void run() {
while (mRunning) {
try {
Realm r = Realm.getInstance(context, "test_db");
r.beginTransaction();
TestData data = r.createObject(TestData.class);
r.commitTransaction();
Logger.e("WRITER THREAD COUNT: " +
r.where(TestData.class).findAll().size());
sleep(LATENCY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
writer.setPriority(Thread.MAX_PRIORITY);
writer.start();
Thread reader = new Thread() {
@Override
public void run() {
while (mRunning) {
try {
Logger.e("READING THREAD COUNT: " + Realm.getInstance(context,
"test_db").where(TestData.class).findAll().size());
sleep(LATENCY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
reader.setPriority(Thread.MAX_PRIORITY);
reader.start();
Is there something needed to do for this to work?
Thanks.
Emanuele from Realm here.
What you are describing is expected behavior :) Since the reader thread doesn't have a Looper
, it has no way to receive notifications from the reader thread and will never update unless you manually execute a refresh
.
In out repo we have several examples (not to mention unit tests) using threads with and without Looper
, illustrating the current best practices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With