【问题标题】:ViewModel observes LiveData from another ViewModelViewModel 从另一个 ViewModel 观察 LiveData
【发布时间】:2018-04-13 13:57:55
【问题描述】:

我有一个Activity,其中包含一些视图和 2 个片段(例如,TextInputFragmentVoiceInputFragment)。

我创建了下一个 ViewModel:

  • ActivityViewModelvoid onInput(String value) 方法
  • interface InputViewModelLiveData<String> getInput() 方法
  • TextInputViewModelVoiceInputViewModel 作为 InputViewModel 的实现

现在我想从两个片段中观察 getInput 并对它们做出反应。 我有下一个想法:

Activity.onCreate:

ActivityViewModel avm = ViewModelProviders.of(this).get(ActivityViewModel.class);

TextInputViewModel tivm = ViewModelProviders.of(this).get(TextInputViewModel.class);
tivm.getInput().observeForever(avm::onInput);

VoiceInputViewModel vivm = ViewModelProviders.of(this).get(VoiceInputViewModel.class);
vivm.getInput().observeForever(avm::onInput);

这个想法正确吗?当配置更改并且我的 ViewModel 尝试重新观察彼此时会发生什么?有什么解决办法吗?

【问题讨论】:

    标签: java android android-architecture-components android-livedata android-viewmodel


    【解决方案1】:

    在研究和阅读android.arch 来源后,我得出了下一个解决方案:

    ActivityViewModel.answer字段的类型改为MediatorLiveData<String>并添加下一个方法:

    public void addAnswerSource(LiveData<String> source) {
        answer.removeSource(source); // to prevent throwing "This source was already added with the different observer" exception
        answer.addSource(source, s -> answer.setValue(s));
    }
    

    现在Activity.onCreate:

    ActivityViewModel avm = ViewModelProviders.of(this).get(ActivityViewModel.class);
    
    TextInputViewModel tivm = ViewModelProviders.of(this).get(TextInputViewModel.class);
    avm.addAnswerSource(tivm.getInput());
    
    VoiceInputViewModel vivm = ViewModelProviders.of(this).get(VoiceInputViewModel.class);
    avm.addAnswerSource(vivm.getInput());
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多