奇怪的 LiveData 行为?

Strange LiveData behaviour?

我正在尝试使用 ViewModel 和 LiveData 实现 MVVM 架构。这两个方法在Activity:

里面
 private void handleResult(BoardViewModel vm) {
        vm.getLiveDataSingleObj("Result").observe(this, new Observer<Object>() {
            @Override
            public void onChanged(@Nullable Object resultObj) {
                Result result = (Result) resultObj;
                if (!result.isCompleted()) return;
                gotoResult();
            }
        });
    }

private void gotoResult() {
        Log.w(LOG_TAG, "Result: Moving to next activity");
        Intent intent = new Intent(boardActivity, ResultActivity.class);
        intent.putExtra("LEVEL", levelIndex);
        intent.putExtra("MAP", mapIndex);
        startActivity(intent);
    }

handleResult 方法被设置为监听指示游戏已经结束并且是时候进入下一个 activity ("gotoResult") 的结果对象。然而,这完全破坏了应用程序的导航,当我返回然后说尝试开始新游戏会话时,我反而立即转到下一个 activity 告诉我我已经赢了。

关于为什么它多次触发并最终停止的任何想法,让我开始一个新的会话。澄清一下,如果我删除 gotoResult 逻辑每次都有效,没有索引超出范围的错误或者你有什么,只有当我添加 goto 时一切都会中断。

视图模型:

private void setupHashTypes() {
        hashLiveData.put(KEY_BOARD, liveDataBoardQuery);
        hashLiveData.put(KEY_STEPS_COUNTER, game.getStepsTakenLiveData());
        hashLiveData.put(KEY_PATH_CHANGE, game.getPathChangedLiveData());
        hashLiveData.put(KEY_VALUE_CHANGE, game.getValueChangeLiveData());
        hashLiveData.put(KEY_TIMER, game.getTimerLiveData());
        hashLiveData.put(KEY_SELECTED, game.getSelectedLiveData());
        hashLiveData.put(KEY_DESELECTED, game.getDeselectedLiveData());
        hashLiveData.put(KEY_HOLD, game.getHoldLiveData());
        hashLiveData.put(KEY_UNHOLD, game.getUnholdLiveData());
        hashLiveData.put(KEY_RESULT, game.getResultLiveData());
    }

    public LiveData<Object> getLiveDataSingleObj(String type) {
        if (hashLiveData.containsKey(type)) {
            return (LiveData<Object>) hashLiveData.get(type);
        }
        throw new IllegalArgumentException("Invalid: key was not found: " + type);
    }

模型有吸气剂,例如:

  private final SingleLiveEvent<Result> resultLiveData = new SingleLiveEvent<>();
    public LiveData<Result> getResultLiveData() {
        return resultLiveData;
    }

你应该在 onDestroy() 方法中删除观察者

从总是将先前设置的值重新发送给新订阅者的 MutableLiveData 更改为没有此行为的 SingleLiveEvent,解决了问题。

class 可以在这里找到:https://github.com/googlesamples/android-architecture/tree/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp