Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm React Native - How to update multiple objects in a loop

I am trying to update multiple object in realm react native using for loop like this:

let pendingReadings = database.objects('Readings').filtered('synced = false');
database.write(() => {
    for (var k=0;k<pendingReadings.length;k++) {
        pendingReadings[k].synced = true;
    }
});

The result should mark all readings synced true. However, it only marks alternative objects as synced (Maybe the previous write isn't complete when the request for next one comes in). What is the best way to update all entries in one go?

like image 922
Irfan Ayaz Avatar asked Jun 17 '16 20:06

Irfan Ayaz


1 Answers

Realm's query results are live-updating. There are various way you could adjust your loop to account for that, but you would get the best performance by using the snapshot() method on results instead...

let pendingReadings = database.objects('Readings')
                              .filtered('synced = false')
                              .snapshot();
database.write(() => {
    for (let i = 0, len = pendingReadings.length; i < len; i++) {
        pendingReadings[i].synced = true;
    }
});

Also notice I adjusted the loop to only retrieve the length once, which would slightly improve performance as well. You could use for...of loops with Realm collections if you'd like, though there is a slight performance penalty in doing so compared to a "raw" loop like the one above.

like image 69
Scott Kyle Avatar answered Nov 12 '22 22:11

Scott Kyle