realm-java icon indicating copy to clipboard operation
realm-java copied to clipboard

Query in realm.executeTransaction success callback is not work, realm is not being update yet for some case

Open luhui opened this issue 10 years ago • 7 comments

Here is the sample code. This code also reproduce the issue #2115

In MyApplication.java

Query in callback can get the data had been saved

Realm realm = Realm.getDefaultInstance();
        Log.e("lh", "before save " + realm.allObjects(Users.class).size());
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Users users = new Users();
                users.setId(UUID.randomUUID().toString());
                users.setName("test");
                realm.copyToRealm(users);
            }
        }, new Realm.Transaction.Callback() {
            @Override
            public void onSuccess() {
                //realm already update
                Log.e("lh", "after save " + realm.allObjects(Users.class).size());
                realm.close();
            }
        });

But in FirstFragment.java, query immediately will failed, delay 1s and re-query will be work.

private void updateEvent() {
        String id = UUID.randomUUID().toString();
        Log.e("lh", "before save " + id + "----" + Realm.getDefaultInstance().allObjects(Event.class).size());
        realm.executeTransaction(realm1 -> {
            Event games = new Event();
            games.setId(id);
            games.setName("test-name!!");
            realm1.copyToRealmOrUpdate(games);
        }, new Realm.Transaction.Callback() {
            @Override
            public void onSuccess() {
                super.onSuccess();
                //Not update yet
                Log.e("lh", "save " + id + " result ...." + realm.allObjects(Event.class).size());

                //Delay 1s, will be work
                new TimerTask(1000).startTask(() -> Log.e("lh", "save " + id + " result after 1s...." + realm.allObjects(Event.class).size()));
            }
        });
    }

But in SecondFragment.java, the subscription can update the new Event object successfully

@Override
    public void onResume() {
        super.onResume();
        subscription = realm.where(Event.class)
                .findAllAsync()
                .asObservable()
                .subscribe(event -> {
                    textView.setText("");
                    for (Event e :
                            event) {
                        textView.append("second - event id: " + e.getId());
                    }
                });
    }

luhui avatar Feb 17 '16 03:02 luhui

in success callback, call realm.refresh() before query can fix this issue, is this the correct answer?

luhui avatar Feb 17 '16 03:02 luhui

Hi @luhui. Sorry for the late reply. Calling refresh should be an acceptable workaround for now. Note that we are currently reviewing a fix for this issue here: https://github.com/realm/realm-java/pull/2294

cmelchior avatar Feb 22 '16 12:02 cmelchior

Hi @luhui we released the fix in 0.87.5 could you please test Cheers,

nhachicha avatar Feb 25 '16 15:02 nhachicha

Hi @nhachicha Thanks for your update, I have test in 0.87.5, and get badversion exception once, but it is hard to reproduce it. I will continue to test, once I found, I will post the sample code on this issue.

luhui avatar Mar 02 '16 01:03 luhui

Hi, I currently use the 0.88 version of realm and I have a same kind of problem. I save several realm objects in database in a worker thread using rxjava. My subscriber registered to receive the updated data with the rx + aync API received the updated data but if just after the saving process I try to load the new added objects from a worker thread with the sync API (always with rxjava) to build a non realm object that will be returned on the main thread the result returned is empty. If I wait for a couple a seconds, I can load the new inserted data.

My registered subscriber loads the data like that :

        Realm.getDefaultInstance().where(ContactRO.class)
                .findAllAsync()
                .asObservable()
                .filter(result -> RealmUtils.isValid(result))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(contacts -> {
                       --> Here contacts is not empty
                }, error -> {
                });

Loading with the sync api is done like that :

Observable.create(subscriber -> {
RealmResult<ContactRO> contacts = Realm.getDefaultInstance()
                .where(ContactRO.class)
                .findAll();
                  --> Here contacts is empty
                   .....
                    subscriber.onNext(nonRealmObject);
                    subscriber.onCompleted();
                }
        )) 
 .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
                .subscribe(contacts -> {
                }, error -> {
                });`

If I call the refresh method before loading data as mentioned in a previous post everything seems to be ok.

Observable.create(subscriber -> {
final RealmInstance realm = Realm.getDefaultInstance();
realm.refresh();
RealmResult<ContactRO> contacts = realm
                .where(ContactRO.class)
                .findAll();
                  --> contacts are loaded
                   .....
                    subscriber.onNext(nonRealmObject);
                    subscriber.onCompleted();
                }
        )) 
 .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
                .subscribe(contacts -> {
                }, error -> {
                });`

Thanks

SilkSama avatar Mar 15 '16 08:03 SilkSama

Hi @SilkSama

but if just after the saving process I try to load the new added objects from a worker thread with the sync

since Realm instance are Thread singleton, you might have grabbed a version of Realm that didn't advance to the latest version (in order to see the changes you've committed after your saving step). Plus you can't register listeners on a non-Looper thread, and our RxJava implementation is based on registering listeners on the RealmObject/RealmResults then calling onNext on the subscriber when the listener is notified.

Example: the following will throw an IllegalStateException

new Thread() {
            @Override
            public void run() {
                Realm bgInstance = Realm.getInstance(Realm.getDefaultInstance().getConfiguration());

                bgInstance.where(ContactRO.class)
                        .findAll()
                        .asObservable()
                        .filter(new Func1<RealmResults<ContactRO>, Boolean>() {
                            @Override
                            public Boolean call(RealmResults<ContactRO> contactROs) {
                                return contactROs.isLoaded();
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<RealmResults<ContactRO>>() {
                            @Override
                            public void call(RealmResults<ContactRO> contactROs) {
                                assert contactROs.size() != 0;
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                throwable.printStackTrace();
                            }
                        });
            }
        }.start();

To observe the saved object from another thread using RxJava you can use the Async API that will use it's own worker thread, no need to call .subscribeOn(Schedulers.io()) like in your example, which will also break the Thread confinement

// from a Looper based thread (ex: UI)

realm.where(ContactRO.class)
    .findAllAsync()
    .asObservable()
    .filter(new Func1<RealmResults<ContactRO>, Boolean>() {
        @Override
        public Boolean call(RealmResults<ContactRO> contactROs) {
            return contactROs.isLoaded() && !contactROs.isEmpty();
        }
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<RealmResults<ContactRO>>() {
        @Override
        public void call(RealmResults<ContactRO> contactROs) {
            assert contactROs.size() != 0;
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            throwable.printStackTrace();
        }
    });

Cheers,

nhachicha avatar Mar 23 '16 18:03 nhachicha

Hi @SilkSama We have released a fix for the BadVersionException in 0.88.3. Please try that and reopen this if you still see it happening.

cmelchior avatar Apr 11 '16 09:04 cmelchior