问题
The answer to this question is providing me with a marvelous guide to how to use services in the Android Architecture Components/Jetpack environment.
It suggests that IntentServices should just plug into ViewModels via Repositories, as if they were any other data source, like a web service.
But neither that answer nor the Jetpack guide upon which it's based have much information about the so-called "Remote Data Source" object that would start and bind to the service, observe its LiveData and cascade it back up to the Repository.
What is it? An ordinary Java object that gets injected into the Repository? A singleton? Some special Lifecycle-aware subclass?
Where does it get the context it needs to start the service?
Is there example code you can point me to? If not, could you just sketch out the basics of what that would look like, including how its lifecycle would be linked to the lifecycle of the service itself, for newbies like me?
Thanks in advance!
回答1:
Instead of an IntentService, you can use an AndroidX component which is lifecycle-aware (works with ViewModel). This component is called WorkManager: https://codelabs.developers.google.com/codelabs/android-workmanager/#0
Another alternative (more challenging) was suggested in your other S.O. post: Use RxJava Observable/Flowable/Processor to push data from IntentService to ViewModel.
回答2:
Have a Base Activity for all your activities and let it bind/unbind to the service. Have an intermediate layer with a repository and a mediator that handles the communication between service and activities. Your ViewModels can register with observer and observe.
来源:https://stackoverflow.com/questions/53292669/android-architecture-components-communication-between-activity-fragment-and-se