如何更新视图模型对象中的自定义值

How to update the custom value in a view model object

我正在尝试创建一个菜单设置,该设置将更新传递给 ViewModelFactory 的值和 return 该大小的新列表。

我尝试传递值并再次调用 ViewModelFactory,但列表大小没有更新。

    factory = new WordViewModelFactory(getApplication(), listSize);

    viewModel = ViewModelProviders.of(this, factory).get(WordViewModel.class);

    ((WordViewModel) viewModel).getWordList().observe(this, new Observer<List<Word>>() {
        @Override
        public void onChanged(@Nullable List<Word> words) {
           Log.d("Shawn", words.toString());
            rvadapter.setWord(words);
        }
    });

菜单选择

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_display_3:
                menuSelection(3);
                return true;
            case R.id.menu_display_5:
                menuSelection(5);
                return true;
            case R.id.menu_object_info:
                Log.d("Shawn", viewModel.toString());
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void menuSelection(int listSize) {
        Log.d("Shawn", "menuSelection num = " + listSize);

    }

视图模型

    private Repository repository;
    private LiveData<List<Word>> wordList;

    public WordViewModel(Application application, int listSize) {
        super(application);
        repository = new Repository(application, listSize);
        wordList = repository.getWordList();
    }

    public LiveData<List<Word>> getWordList() {
        return wordList;
    }

    public LiveData<List<Word>> updateList(int newListSize) {

        return wordList.postValue(newListSize);
    }

存储库

    private Repository repository;
    private LiveData<List<Word>> wordList;


    public WordViewModel(Application application, int listSize) {
        super(application);
        repository = new Repository(application, listSize);
        wordList = repository.getWordList();
    }

    public LiveData<List<Word>> getWordList() {
        return wordList;
    }

DAO

    @Query("SELECT * FROM word_table ORDER BY word ASC LIMIT :size")
    LiveData<List<Word>> getAllNotes(int size);

无需再次调用viewModelFactory。要更新 WordViewModel 中的值,您需要在 viewModel 中创建一个 setter 并更新 LiveData。

将此函数添加到您的 WordViewModel

public void setWordList(Application application, int listSize) {
    repository = new Repository(application, listSize);
    wordList = repository.getWordList();
}

(注意:每次调用上面的函数都会创建repository的对象,这种方式不好,需要改变结构)

然后从 activity/fragment 调用此函数,如下所示

((WordViewModel) viewModel).setWordList(application, listSize)

我觉得ViewModel这个概念不是setter,更像是update

您已经 Observed 您的 ViewModel.getWordList() 在您的 View 中,这是正确的。

由于 wordListLiveData,您使用

wordList.postValue(newValue)

让所有观察者都知道它有新的更新。