What is the difference between the LifecycleService and the Service class?

Viewed 4812

I have been reading the documentation on Android Developer page, but besides the fact that one extends from Service and implements LifecycleOwner and the other extends ContextWrapper, I have not been able to understand when to use one or the other.. Do both of them serves the same purpose?

1 Answers

LifecycleService has additional functionality, so it's preferred if you need that functionality.

A LifecycleOwner allows other classes to subscribe to its lifecycle state. For example, some component in your application could automatically tear itself down, free up native memory, unregister listeners, etc. by subscribing to the Service's destroyed lifecycle stage. Then your Service code wouldn't have to worry about it.

You also have access to lifecycleScope in a LifecycleService, and that can be used to start coroutines that will automatically be cancelled when the Service is stopped.

ViewModel and LiveData are designed around the use of lifecycles, so you could theoretically use them with a LifecycleService, but that would probably be counter-productive since they are intended for UI.

Related