/while-in-use-location

Codelab:

Primary LanguageKotlinApache License 2.0Apache-2.0

While-in-use Location + Room, Flow, and Hilt

This repository is derived from the while-in-use location codelab and repository:

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:

  1. Room + Flow observer implementation - LocalBroadcastManager was originally used to share new locations obtained in the ForegroundOnlyLocationService with the MainActivity. As discussed here, this "event bus" pattern is no longer recommended because it encourages app architecture layer violations. This project replaces LocalBroadcastManager with a data repository implemented via Room. The ForegroundOnlyLocationService persists new locations to Room, and MainActivity 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.
  2. 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.
  3. 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.
  4. 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.