Writing and reading between streams with Android Realm

I am doing some investigation of Realm streaming and ran into a problem.

In this simple example, I have 2 Thread objects, one for writing and one for reading. The Thread reader always gets the number of written objects as 0, but inside the recording area, the size() for the elements in the database is correct. When I restart the application, the reader gets the first ok counter before any inserts.

 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 anything that needs to be done for this?

Thanks.

+5
source share
1 answer

Emanuele of the Kingdom is here.

What you are describing is the expected behavior :) Since the reader thread does not have a Looper , it is not able to receive notifications from the reader stream and will never be updated unless you manually refresh .

In repo mode, we have a few examples (not to mention unit tests) using streams with and without Looper that illustrate current best practices.

+8
source

Source: https://habr.com/ru/post/1211866/


All Articles