I have an app that runs a service, which should continue working even when the app is closed. I need to share info between them, and I want to try doing this using a ViewModel. I know how to share a ViewModel between fragmments, but between an activity and service escapes me. Does anyone know?
Asked
Active
Viewed 3,084 times
6
-
What's the role of a _view_model in conjunction with a service? – Haukinger Dec 07 '17 at 06:59
-
I have a class that tracks sensor data that needs to be accessed by MainActivity and also by the service. I can create two objects, but since it's the same data, it'd be redundant and I'd have to worry about starting/stopping each properly. A shared ViewModel would be preferred – Elliptica Dec 07 '17 at 22:22
-
1Sure, you only store the data once. But I just can't imagine what a service might want to do with a view model. I'd rather put the data in a (classic, non-android) service and acces that from your (android) service and your view model. – Haukinger Dec 08 '17 at 16:20
1 Answers
0
@Elliptica
My solution:
1) Your activities and services must run on same process !
2) Make a BaseSupportViewModelService
class that has ViewModelStore
to store your ShareViewModel
.
3) Your ViewModel
must be shareable! How to share ViewModel
between two activities (maybe three) or service.
Here's a link1
Here's a link2
Hope it helps you.

hansey li
- 17
- 4