简体   繁体   中英

Access and modify a variable from inner anonymous class

I have the following code:

boolean gameSuccess = false;
@Override
    public boolean saveMission(final Mission mission) {
        realm = Realm.getInstance(realmConfiguration);

        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealm(mission);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "onSuccess: mission saved");
                realm.close();
                missionSuccess = true;
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                Log.d(TAG, "onError: mission failed");
                realm.close();
                missionSuccess = false;
            }
        });
        return gameSuccess;
    }

gameSuccess is always false even if onSuccess was called. What is the way to get this done?

Async isn't blocking, so your code is wrong. The transaction doesn't happen before the return, but any unspecified time later, which is why it is always false.

You either need to provide a callback to your method or convert the transaction to blocking

public void saveMission(final Mission mission, Callback callback) {
     realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealm(mission);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "onSuccess: mission saved");
                realm.close(); 
                callback.onSuccess();
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                Log.d(TAG, "onError: mission failed");
                realm.close();
                callback.onError();
            }
        });
}

or

realm.executeTransaction(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM