将参数传递给AndroidViewModel

时间:2018-05-16 10:04:11

标签: android persistence viewmodel android-room

我跟随谷歌tutorial进行会议室持久性但我已经卡住了,现在我让教程全部正常工作但是我需要扩展它并且能够将参数传递给ViewModel因为我需要的是能够向回购提交不同的查询,也许我错了,但现在我在ViewModel应该能够做到这一点阅读他的领域并选择正确的方法与回购交谈。

WordViewModel:

public class WordViewModel extends AndroidViewModel {

 private WordRepository mRepository;

   private LiveData<List<Word>> mAllWords;
   public int mode = 0;       

   public WordViewModel (Application application) {
       super(application);
       mRepository = new WordRepository(application);
       if (mode==0)
         mAllWords = mRepository.getAllWords();
       else
         mAllWords = mRepository.getSomethingElse();
   }

   LiveData<List<Word>> getAllWords() { return mAllWords; }

   public void insert(Word word) { mRepository.insert(word); }
}

然后在活动中触发我们得到的模型视图

mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);
mWordViewModel.mode=1; //MY ADDITION, not working
...
mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
   @Override
   public void onChanged(@Nullable final List<Word> words) {
       // Update the cached copy of the words in the adapter.
       adapter.setWords(words);
   }
});
...

现在的问题是我所进行的字段访问和编辑(&#34;模式&#34;字段)不起作用,就像{{{}字段正在重置1}}实际上是被调用的,所以它始终是0.我想念的是什么?什么是最简单的解决方法,考虑到该模式仅用于解释,并且最终我需要大量参数(因此创建各种ViewModel不是一种选择)

1 个答案:

答案 0 :(得分:1)

我认为您正在遇到与ViewModel本身的生命周期相关的问题以及您正在使用的不同变量等。我建议使用类似MediatorLiveData的东西来做你正在尝试做的事情......例如(这是在Kotlin btw,因为我正在使用类似的逻辑)

class WordViewModel : ViewModel() {
    .....

    val mode: MutableLiveData<Int> = MutableLiveData()

    val mAllWords = MediatorLiveData<List<Word>>().apply {
        this.addSource(mode) {
            if (mode.value == 0)
                this.value = mRepository.getAllWords()
            else 
                this.value = mRepository.getSomethingElse()        
        }
    }



    init {
        mode.value = 0
    }

    fun setMode(m: Int) {
        mode.value = m
    }

}

我在这里执行此操作的代码是https://github.com/joreilly/galway-bus-android/blob/master/base/src/main/java/com/surrus/galwaybus/ui/viewmodel/BusStopsViewModel.kt