【问题标题】:Passing arguments to AndroidViewModel将参数传递给 AndroidViewModel
【发布时间】:2018-05-16 10:04:11
【问题描述】:

我正在关注 google tutorial 的房间持久性,但我卡住了,现在我的教程一切正常,但我需要扩展它并能够将参数传递给 ViewModel,因为我需要能够向 repo 提交不同的查询,也许我错了,但现在我在ViewModel 中这样做,它应该能够读取他的字段并选择正确的方法与 repo 交谈.

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

现在的问题是我所做的字段访问和编辑(“模式”字段)不起作用,就像实际调用 ViewModel 时该字段正在重置,所以它始终为 0。什么我失踪了吗?考虑到该模式仅用于解释并且最终我需要很多参数,最简单的解决方法是什么(因此创建各种ViewModel 不是一种选择)

【问题讨论】:

  • mode设为静态并在初始化前更改其值
  • @AbuYousuf “在初始化之前”是什么意思?仅将字段更改为静态什么都不做
  • 在初始化mWordViewModel之前添加WordViewModel.model = 1
  • @AbuYousuf 成功了!

标签: android persistence viewmodel android-room


【解决方案1】:

我认为您遇到了与 ViewModel 本身的生命周期以及您正在使用的不同变量等相关的问题。我建议使用 MediatorLiveData 之类的东西来做你想做的事情......例如(这是在 Kotlin 中顺便说一句,因为这就是我用于类似逻辑的东西)

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

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 2020-11-08
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2013-11-19
    相关资源
    最近更新 更多