本文介绍了服务内的Android ViewModel(可选)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务,可提供大多数时间对用户可见的UI.

I have a service which provides UI that is visible to user most of the time.

遇到问题时,我正在尝试新的应用程序体系结构.

I was experimenting with new Application Architecture when I came with a problem.

MyModelviewModel viewModel = ViewModelProviders.of(this).get(MyModelviewModel.class);

但是您知道this只能是AppCompatFragment

有其他选择吗?或者我可以像将Im放在ViewModel

Is there some alternative? or can I put observer directly on my LiveData like Im puting on ViewModel

viewModel.getList().observe(Playground.this, new Observer<List<TestEntity>>() {
    @Override
    public void onChanged(@Nullable List<TestEntity> items) {
        recyclerViewAdapter.addItems(items);
    }
});

推荐答案

LiveData可以独立使用,而无需ViewModel,可以在提供适当的LifecycleOwner实例的同时使用observeForever(Observer<T> observer)observe(LifecycleOwner owner, Observer<T> observer),您可以在服务或视图中实现LifecycleOwner.

LiveData can be use independently without ViewModel,you can use observeForever(Observer<T> observer), or observe(LifecycleOwner owner, Observer<T> observer) while you provide a proper LifecycleOwner instance, you can implement LifecycleOwner in your service or view.

ViewModelProviders仅为每个FragmentActivity提供ViewModel的缓存,您可以直接通过new MyModelviewModel()创建ViewModel.

ViewModelProviders just provides a cache of ViewModel for each Fragment or Activity, you can create your ViewModel directly by new MyModelviewModel().

这篇关于服务内的Android ViewModel(可选)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 23:22