Android ViewModel inside Service (Alternative)

丶灬走出姿态 提交于 2019-12-04 10:32:12

问题


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

But as you know this can be only AppCompat or Fragment

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

回答1:


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 just provides a cache of ViewModel for each Fragment or Activity, you can create your ViewModel directly by new MyModelviewModel().



来源:https://stackoverflow.com/questions/48716548/android-viewmodel-inside-service-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!