Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the realm is already in a write transaction

the realm is already in a write transaction.

How can i avoid this error? is there a way to check realm is in write traction? if realm is in write transaction then closed first then do other work. Now after getting this error "the realm is already in a write transaction." then other tasks connected with realm also not working.

like image 412
Aye Avatar asked Sep 07 '16 09:09

Aye


3 Answers

Here is one possible solution that I came across in this github discussion:

extension Realm {
    public func safeWrite(_ block: (() throws -> Void)) throws {
        if isInWriteTransaction {
            try block()
        } else {
            try write(block)
        }
    }
}

use it like this:

try! realm.safeWrite{
    //your write code goes here
}

now safeWrite will check if there is active transaction and will either start one or just execute the code passed in.

like image 158
vir us Avatar answered Nov 07 '22 13:11

vir us


The rule of thumb for Realm is only one write transaction open on an RLMRealm at any given time. You might need to reconsider your logic if you're hitting this error. You shouldn't ever intentionally be trying to open up a second write transaction on a RLMRealm that's already open on the same thread. Doing it on separate threads is fine, but the thread the second write transaction is on will be blocked until the first one completes.

If there's something in your implementation that isn't set right, it's also possible that a transaction you've assumed had completed might have had an error and was left open. Like Sebastian said, you can check this with -[RLMRealm inWriteTransaction], but in this case, you should definitely backtrack your code to see why that is happening.

like image 38
TiM Avatar answered Nov 07 '22 11:11

TiM


If you are doing some write tasks in the same thread, you can add them to NSMutableArray, a then use addOrUpdateObjectsFromArray. On the other side, you can check to avoid write conflicts by firing inWriteTransaction on realm object.

like image 43
Sebastian K Avatar answered Nov 07 '22 12:11

Sebastian K