Niko
Niko

Reputation: 8153

Writing and reading between threads with Android Realm

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.

Upvotes: 5

Views: 1137

Answers (1)

Emanuelez
Emanuelez

Reputation: 1651

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.

Upvotes: 8

Related Questions