Reputation: 1070
I have a RealmObject
User
that I store in a singleton and access throughout the application -- it was retrieved on the UI thread. The object represents the logged in user, and has a one-to-many relationship with the Item
class. When changing it in a transaction such as in:
RealmSingleton.getUserInstance().executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
User user = realm.where(User.class).equalTo("mId",UserSingleton.getUser().getId()).findFirst();
user.deleteItem(mItem.getClassId());
}
});
This won't work because I'm accessing it inside of the transaction that occurs in another thread. Just to clarify, what I need to do here is store the user's id outside of the transaction and then access that stored variable within the transaction when making the query, like so?
Integer userId = UserSingleton.getUser().getId();
Integer classId = mItem.getClassId();
RealmSingleton.getUserInstance().executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
User user = realm.where(User.class).equalTo("mId",userId).findFirst();
user.deleteItem(classId);
}
});
Upvotes: 1
Views: 439
Reputation: 20126
Yes, that is correct. You cannot access an object on multiple threads, so in your case storing a reference to the ID and use that to requery the object is the right approach.
Upvotes: 2