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);
}
});
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.
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.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With