Cannot create asynchronous query while in a write transaction in /Users/Nabil/Dev/realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_Collection.cpp line 274
Hi, I keep getting this crash and has affected significant number of users. Usecase:
- Profile page which fetches data from two different asynchronous apis.
- The above crash is at changeListener for the object for results of 2nd API.
Wanted to confirm, if there is data write going on in realm in a execute transaction block, will this crash happen at the change listener of the other objects. I was under the perception that execute transaction block is in itself a seperate thread and ideally asynchronous query error should not be thrown. Can you correct me on what is the core reason of this issue. Thanks
This crash happens if you run an asynchronous query inside a write transaction. It is not related to the change listener as such.
// Async query
realm.beginTransaction();
RealmResults<Person> people = realm.where(Person.class).findAllAsync(); // Will throw
realm.commitTransaction();
// Use sync query instead
realm.beginTransaction();
RealmResults<Person> people = realm.where(Person.class).findAll(); // Will not throw
realm.commitTransaction();
This restriction is in place because when triggering notification listeners, we need to have a stable version to calculate changes from, and inside a write transaction, you are in the middle of changing values.
But @cmelchior, i have not used any async transaction in my application and also all crashes in this category occur only at page where there are more than one change listener and crash report points to the change listener LOC.
async query like findAllAsync
I cannot really tell you anything without code, especially if Rx is involved.
There is no Rx involved. I can share the bit pieces of code of my transaction write, but I doubt if it will provide any info.
Well anything to do with transactions in change listeners is a good bet 😄
Sure.
Terminating app due to an uncaught exception 'java.lang.IllegalStateException', reason: 'Cannot create asynchronous query while in a write transaction in /Users/Nabil/Dev/realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_Collection.cpp line 274'
Transaction update code for requests in same page:
Realm realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
System.out.println("realm Group Members updated");
realm.where(GroupMember.class).equalTo("groupId", groupId).findAll().deleteAllFromRealm();
Iterator
Another tansaction udpate code: ApplicationDataHandler.getRealm().executeTransaction(realm -> { realm.insertOrUpdate(networkGroupCache); });
the crash happens at : groupMembers.addChangeListener(element -> { loadMemberImages(); });
All realm transaction in the app are sync but coz this data is huge i have put this under async execute.
What is loadMemberImages();?
Also, add ``` around your code so that it is formatted.
it is a function which displays the thumbnail images of the members of the group.
okay, so the formatted code is
Realm realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
@override
public void execute(Realm realm) {
System.out.println("realm Group Members updated");
realm.where(GroupMember.class).equalTo("groupId", groupId).findAll().deleteAllFromRealm();
Iterator iterator = response.connections.iterator();
while (iterator.hasNext()) {
AgentProfileCache agentProfileCache = iterator.next();
realm.insertOrUpdate(new GroupMember(agentProfileCache.getId(), groupId));
if (agentProfileCache.getId().equals(ApplicationDataHandler.getMyAgentId())) {
iterator.remove();
} else {
realm.insertOrUpdate(agentProfileCache);
}
}
}
}
}
realm.close();
But where exactly is
groupMembers.addChangeListener(element -> {
loadMemberImages();
});
?
That is in the view of my app. the realm update code is in the data model whereas the change listener is in the view part and the load Member image function does only one job -> display image,
Like, code context.
did not get you. this is the loadMemberImage function for (String key : urls.keySet()) { LayoutOnlyImageBinding imageBinding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.layout_only_image, binding.memberImageLayout, false); CollectionUtils.setAgentAvatar(urls.get(key), imageBinding.image, key, 5); binding.memberImageLayout.addView(imageBinding.getRoot()); }
How to solve this problem? I also encountered the same error, I am using rxjava.
Don't call findAllAsync inside a write transaction.
I will delete the inserted code or will report an error.
The situation is like this, when the activity is killed in the background, then enter the activity add addChangeListener is reported error.
Code
private RealmResults<ScreenAd> mScreenAds;
// run on onCreate:
mScreenAds = getUserRealm().where(ScreenAd.class)
.greaterThan("endTime", System.currentTimeMillis())
.equalTo("canShow", true)
.isNotEmpty("adImageUrl")
.findAllSorted("timestamp", Sort.ASCENDING);
// run on onStart:
if (mScreenAds != null) {
mScreenAds.addChangeListener(new RealmChangeListener<RealmResults<ScreenAd>>() {
@Override
public void onChange(RealmResults<ScreenAd> screenAds) {
showScreenAd();
}
});
}
Add error log
Caused by: java.lang.IllegalStateException: Cannot create asynchronous query while in a write transaction in /home/cc/repo/realm/release/realm/realm-library/src/main/cpp/io_realm_internal_Collection.cpp line 329
at io.realm.internal.Collection.nativeStartListening(Native Method)
at io.realm.internal.Collection.addListener(Collection.java:486)
at io.realm.internal.Collection.addListener(Collection.java:493)
at io.realm.RealmResults.addChangeListener(RealmResults.java:175)
We currently have a limitation that means you cannot add listeners inside a write transaction due to the way listeners work, it looks like you are running into that here.
We currently have a limitation that means you cannot add listeners inside a write transaction due to the way listeners work, it looks like you are running into that here.
I have no transaction now. Still report an error, please see https://github.com/realm/realm-java/issues/5771#issuecomment-428901359
Are you 100% sure that there is no transaction open there?
I read the document, and I also judged whether there was a transaction in execution, and there was no mistake in making the judgement. Realm.isInTransaction
If the write transaction happened on the same thread, the listener will be called synchronously when the transaction is committed. However, in some cases the listener may be called when the transaction starts—if the Realm is advanced to the latest version, or Realm entities being observed were modified or deleted in a way that triggers notifications. In those cases, the listener runs within the context of the current write transaction, so an attempt to begin a new write transaction within the notification handler will throw an exception. You can use the Realm.isInTransaction method to determine if your code is executing within a write transaction.
Thanks very much!!!