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?
Can I share a ViewModel between an activity and a service?
Asked Answered
What's the role of a _view_model in conjunction with a service? –
Mayce
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 –
Dimer
Sure, 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. –
Mayce
@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.
© 2022 - 2024 — McMap. All rights reserved.