Encapsulate callbacks calls into try/catch block

This commit is contained in:
Maxime NATUREL 2022-06-09 09:54:49 +02:00
parent 260f73b0c2
commit 755d743b06

View File

@ -71,16 +71,16 @@ class LocationTracker @Inject constructor(
Timber.d("start()") Timber.d("start()")
if (locationManager == null) { if (locationManager == null) {
callbacks.forEach { it.onNoLocationProviderAvailable() }
Timber.v("LocationManager is not available") Timber.v("LocationManager is not available")
onNoLocationProviderAvailable()
return return
} }
val providers = locationManager.allProviders val providers = locationManager.allProviders
if (providers.isEmpty()) { if (providers.isEmpty()) {
callbacks.forEach { it.onNoLocationProviderAvailable() }
Timber.v("There is no location provider available") Timber.v("There is no location provider available")
onNoLocationProviderAvailable()
} else { } else {
// Take GPS first // Take GPS first
providers.sortedByDescending { getProviderPriority(it) } providers.sortedByDescending { getProviderPriority(it) }
@ -133,7 +133,7 @@ class LocationTracker @Inject constructor(
* Please ensure adding a callback to receive the value. * Please ensure adding a callback to receive the value.
*/ */
fun requestLastKnownLocation() { fun requestLastKnownLocation() {
lastLocation?.let { location -> callbacks.forEach { it.onLocationUpdate(location) } } lastLocation?.let { locationData -> onLocationUpdate(locationData) }
} }
fun addCallback(callback: Callback) { fun addCallback(callback: Callback) {
@ -190,7 +190,7 @@ class LocationTracker @Inject constructor(
val locationData = location.toLocationData() val locationData = location.toLocationData()
lastLocation = locationData lastLocation = locationData
callbacks.forEach { it.onLocationUpdate(location.toLocationData()) } onLocationUpdate(locationData)
} }
override fun onProviderDisabled(provider: String) { override fun onProviderDisabled(provider: String) {
@ -203,7 +203,28 @@ class LocationTracker @Inject constructor(
locationManager?.allProviders locationManager?.allProviders
?.takeIf { it.isEmpty() } ?.takeIf { it.isEmpty() }
?.let { ?.let {
callbacks.forEach { it.onNoLocationProviderAvailable() } Timber.e("all providers have been disabled")
onNoLocationProviderAvailable()
}
}
private fun onNoLocationProviderAvailable() {
callbacks.forEach {
try {
it.onNoLocationProviderAvailable()
} catch (error: Exception) {
Timber.e(error, "error in onNoLocationProviderAvailable callback $it")
}
}
}
private fun onLocationUpdate(locationData: LocationData) {
callbacks.forEach {
try {
it.onLocationUpdate(locationData)
} catch (error: Exception) {
Timber.e(error, "error in onLocationUpdate callback $it")
}
} }
} }