"Unable to create asynchronous request during write transaction"

After moving my OS OS application from version 2.2 to swift 3.0 (the real-time version also changed from 1.0.2 to 2.1.1), some of the write transactions started to throw an exception: "Unable to create an asynchronous request during a write transaction." But it worked fine before the migration.

let realm = try Realm() let allMessages = realm.objects(Message.self) let messages = allMessages.filter("(state == 1) AND (dateSent <= %@)", dateSent) try realm.write ({ messages.forEach { message in message.state = .seen } }) 

At the beginning of the transaction, it throws an exception. Why is this happening and how can I fix it?

+6
source share
4 answers

The same problem occurred in my code, and it turned out that the start of the write transaction triggered a collection notification, which in turn created new RLMResults and added a notification block to it, which means that I called addNotificationBlock inside the write and failure transaction .

If you can reproduce, set a breakpoint in results.cpp - void Results::prepare_async() , where the exception is thrown, and see what your code is trying to do.

+2
source

It seems that you are mutating messages in forEach , this could be the cause of the crash.

Try something like this:

 let realm = try Realm() let allMessages = realm.objects(Message.self) let results = allMessages.filter("(state == 1) AND (dateSent <= %@)", dateSent) let messages = Array(results) try realm.write ({ messages.forEach { message in message.state = .seen } }) 

This may not be the best solution, since you are loading all messages into memory, but should work.

0
source

I think you just need to move requests into a transaction.

 let realm = try Realm() try realm.write ({ let allMessages = realm.objects(Message.self) let messages = allMessages.filter("(state == 1) AND (dateSent <= %@)", dateSent) messages.forEach { message in message.state = .seen } }) 
0
source

This can happen if you run findAllAsync inside the change listener https://github.com/realm/realm-java/issues/5771#issuecomment-442004078

I handled the requests using async / await and now everything is fine.

0
source

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


All Articles