代码之家  ›  专栏  ›  技术社区  ›  Tiago Redaelli

奇怪的LiveData行为?

  •  0
  • Tiago Redaelli  · 技术社区  · 7 年前

    我正在尝试使用ViewModel和LiveData实现MVVM体系结构。这两种方法位于活动中:

     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);
        }
    

    该模型具有getter,例如:

      private final SingleLiveEvent<Result> resultLiveData = new SingleLiveEvent<>();
        public LiveData<Result> getResultLiveData() {
            return resultLiveData;
        }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   H. Ekici    7 年前

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

        2
  •  1
  •   Tiago Redaelli    7 年前

    将始终将以前的设置值重新发送给新订阅者的MutableLiveData更改为不具有此行为的SingleLiveEvent,解决了这个问题。

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