20

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);
    }
});
CBeTJlu4ok
  • 1,072
  • 4
  • 18
  • 51

2 Answers2

23

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

Riki
  • 2,774
  • 1
  • 24
  • 38
  • In case of creating new `ViewModel`, it will be destroyed with my activity rotation am I right? or how I am supposed to get same instance other way – CBeTJlu4ok Feb 10 '18 at 03:07
  • If you want to create `ViewModel` in activity, use `ViewModelProviders.of(activity).get(MyModelviewModel.class);`, it will get same instance after activity rotation. If you want to create `ViewModel` in service, just new it, I think we don't need to cache the viewmodel in service. – Riki Feb 10 '18 at 06:28
  • @AvatarQing Got it. But suppose if I use a ViewModel with just the constructor (without the ViewModelProviders) then would coroutine scope: [ViewModelScope](https://developer.android.com/topic/libraries/architecture/coroutines#viewmodelscope) will work properly? – Sahil Sharma Feb 28 '21 at 10:30
  • @SahilSharma You should invoke viewmodel's clear() method manually to make viewModelScope work properly. You can review viewModelScope's source code to verify. – Riki Jul 02 '21 at 09:24
4

Initialize with

new ViewModel()

in

onStartCommand
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
Shawn Muktadir
  • 140
  • 2
  • 7