问题描述
我有一项服务,可提供大多数时间对用户可见的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
只能是AppCompat
或Fragment
有其他选择吗?或者我可以像将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
仅为每个Fragment
或Activity
提供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(可选)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!