Skip to content

Instantly share code, notes, and snippets.

@barbeau
Last active August 16, 2021 16:37
Show Gist options
  • Save barbeau/53663c9e4fafbac749659f8b57761168 to your computer and use it in GitHub Desktop.
Save barbeau/53663c9e4fafbac749659f8b57761168 to your computer and use it in GitHub Desktop.
Flow - lightweight architecture article -
@AndroidEntryPoint
class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
...
// Data store from which to receive location updates via Flow, injected via Hilt
@Inject
lateinit var repository: LocationRepository
// Get a reference to the Job from the Flow so we can stop it from UI events
private var locationFlow: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
...
button.setOnClickListener {
val tracking = SharedPreferenceUtil.getLocationTrackingPref(this);
if (!tracking) {
subscribeToLocationUpdates()
} else {
unsubscribeToLocationUpdates()
}
}
}
private fun subscribeToLocationUpdates() {
// Observe locations via Flow as they are generated by the repository
locationFlow = repository.getLocations()
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.onEach {
logResultsToScreen("Foreground location: ${it.toText()}")
}
.launchIn(lifecycleScope)
foregroundOnlyLocationService?.subscribeToLocationUpdates()
}
private fun unsubscribeToLocationUpdates() {
locationFlow?.cancel()
foregroundOnlyLocationService?.unsubscribeToLocationUpdates()
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment