The correct way to obtain a ViewModel instance outside of an Activity or a Fragment
Question is how should I get the LocationViewModel instance in a non-activity class like this BroadcastReceiver?
You shouldn't do that. Its bad design practice.
Is it correct to call locationViewModel = ViewModelProviders.of(context).get(LocationViewModel.class) where context is the context that I receive from onReceive (Context context, Intent intent) of the BroadcastReceiver?
No. It won't help
You can achieve your desired outcome as follows:
Separate your Room DB operation from ViewModel
in a separate singleton class. Use it in ViewModel
and any other place required. When Broadcast is received, write data to DB through this singleton class rather than ViewModel
.
If you are observing for the LiveData
in your Fragment, then it will update your views too.