Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewModel inside Service (Alternative)

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);
    }
});
like image 467
CBeTJlu4ok Avatar asked Feb 10 '18 02:02

CBeTJlu4ok


People also ask

Can Android use ViewModel in service?

It is not recommended using a ViewModel in a service. You could call your repository from your service itself. The ViewModel should be used closely with an Activity or a Fragment, so it's destined to live in the UI layer of your application. Therefore, I don't recommend using the ViewModel in a Service.

Is ViewModel destroyed?

ViewModel is a separate class which has an instance of it in the activity and has no reference for view in it. So even though activity onDestroy() and onCreate() happens on configuration change, the instance of ViewModel doesn't get destroyed or garbage collected.

What is the difference between AndroidViewModel and ViewModel?

The AndroidViewModel extends ViewModel , so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the Application context as a parameter.

How do you observe LiveData in service?

You usually create an Observer object in a UI controller, such as an activity or fragment. Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes.


1 Answers

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().

like image 120
Riki Avatar answered Oct 01 '22 18:10

Riki