我创建了一个位置存储库,负责收集位置数据并将其传输给任何收听的人,现在的代码如下所示:
@Singleton
class LocationRepository @Inject constructor(
app: Application
) {
private val _location = MutableStateFlow<Location?>(null)
private val subscribers = AtomicInteger()
val location: Flow<Location?> = _location.onSubscription {
if (subscribers.getAndIncrement() == 0)
startUpdates()
}.onCompletion {
if (subscribers.decrementAndGet() == 0)
stopUpdates()
}
private val client = LocationServices.getFusedLocationProviderClient(app)
private val locCb = object : LocationCallback() {
override fun onLocationResult(var1: LocationResult?) {
newLocationResult(var1)
}
override fun onLocationAvailability(var1: LocationAvailability) {}
}
private val request = LocationRequest.create()
init {
request.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
request.interval = 5000L
request.fastestInterval = 2500L
}
private fun startUpdates() { //code to start getting location updates }
private fun stopUpdates() { //code to stop getting location updates }
}
现在我正在处理当前的订阅者数量AtomicInteger
,有没有办法在第一个订阅者订阅和最后一个订阅者取消订阅时自动运行startUpdates
代码和代码?stopUpdates