奇怪的LiveData行为?

时间:2018-05-06 16:00:28

标签: java android mvvm viewmodel android-livedata

我尝试使用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方法设置为侦听结果对象,指示游戏已结束,是时候进入下一个活动(“gotoResult”)。然而,这完全打破了应用程序的导航,当我回去然后说尝试开始新的游戏会话时,我立即转到下一个活动,告诉我我已经赢了。

关于为什么它会多次触发并最终停止的任何想法,让我开始一个新的会话。为了澄清一下,如果我删除了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;
    }

2 个答案:

答案 0 :(得分:1)

你应该在onDestroy()方法

中删除观察者

答案 1 :(得分:1)

从MutableLiveData(总是重新发送以前的设置值到新订阅者)更改为没有这种行为的SingleLiveEvent解决了这个问题。

可在此处找到课程:https://github.com/googlesamples/android-architecture/tree/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp