AndroidViewModel 更新 MutableLiveData 对象

AndroidViewModel updating MutableLiveData object

我在 ViewModel 中初始化布尔值 属性 时遇到问题。我不确定解决这个问题的正确方法。

我在主 activity 上有一个开关控件,如果我更改开关,我想更改布尔 startsWith 值。根据boolean值我会调用对应的dao函数

我正在尝试初始化该值,但不确定如何执行此操作。我应该观察布尔值,我应该使用双向绑定,这个 属性 应该是 MutableLiveData 吗?

wordListViewModel = ViewModelProviders.of(this).get(WordListViewModel.class);
wordListViewModel.setStartsWith(true);

我收到这个错误,甚至无法启动 Activity:

Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference

代码:

public class WordListViewModel extends AndroidViewModel {

    final MutableLiveData<String> searchText = new MutableLiveData<>();
    final MutableLiveData<Boolean> startsWith = new MutableLiveData<>();

    private final LiveData<List<WordEntity>> list;

    private AppDatabase appDatabase;

    public WordListViewModel(Application application) {
        super(application);

        appDatabase = AppDatabase.getDatabase(this.getApplication());

        if (startsWith.getValue() == true)
            list = Transformations.switchMap(searchText, searchText -> {
                return appDatabase.wordDao().getWordsStartingWith(searchText);
            });
        else
            list = Transformations.switchMap(searchText, searchText -> {
                return appDatabase.wordDao().getWordsLike(searchText);
            });

    }

我想我明白了。检查必须在 switchMap 函数内。 其余代码仅在模型初始化时运行。

我更改了我的代码并且它起作用了:

    if (startsWith.getValue() == null)
        startsWith.setValue(true);

    list = Transformations.switchMap(searchText, searchText -> {
        if (startsWith.getValue() == true)
            return appDatabase.dictWordDao().getWordsStartingWith(searchText);
        else
            return appDatabase.dictWordDao().getWordsLike(searchText);
    });