While-in-use Location + Room, Flow, and Hilt
This repository is derived from the while-in-use location codelab and repository:
- https://developers.google.com/codelabs/while-in-use-location
- https://github.com/googlecodelabs/while-in-use-location
tl;dr
This project replaces LocalBroadcastManager
with Room + Flow for listening to location updates in an Activity
that are generated by a fused location provider callback in a Service
.
Description
The detailed differences between the original while-in-use-location code lab and this project are:
- Room + Flow observer implementation -
LocalBroadcastManager
was originally used to share new locations obtained in theForegroundOnlyLocationService
with theMainActivity
. As discussed here, this "event bus" pattern is no longer recommended because it encourages app architecture layer violations. This project replacesLocalBroadcastManager
with a data repository implemented via Room. TheForegroundOnlyLocationService
persists new locations to Room, andMainActivity
is notified of changes in the Room database via Kotlin Flow (see references here and here). Flow.flowWithLifecycle is used to observe the Flow in the Activity to make sure all observing resources are torn down when the Activity is destroyed. - Hilt for dependency injection - To make the data repository (Room database) available to the service and activity, Hilt is used. See additional useful resources on Hilt and Room in this video, in this codelab, and in this repo example.
- Lifecycle extensions - To access the data repository within the service and activity using scoped coroutines, the KTX Lifecycle extensions are used. This ensures that any coroutines that are running within the scope of the activity or service lifecycle will be destroyed when those respective objects are destroyed.
- Other minor changes:
- Location update frequency increased to once per second to make it easier to observe data flow
- MainActivity text view is now scrollable
See the code diff of the two projects that highlights the changes when replacing LocalBroadcastManager
with Room + Flow here.