Last active
August 16, 2021 16:37
-
-
Save barbeau/53663c9e4fafbac749659f8b57761168 to your computer and use it in GitHub Desktop.
Flow - lightweight architecture article -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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