0

我创建了一个位置存储库,负责收集位置数据并将其传输给任何收听的人,现在的代码如下所示:

@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

4

1 回答 1

1

请检查subscriptionCount的属性MutableSharedFlow,它可能是您正在寻找的。它具有类型StateFlow<Int>并发出此共享流的订阅者(活动收集器)的数量。例子:

_location.subscriptionCount
    .map { count -> count > 0 } // map count into active/inactive flag
    .distinctUntilChanged() // only react to true<->false changes
    .onEach { isActive -> // configure an action
        if (isActive) startUpdates() else stopUpdates()
    }
    .launchIn(scope) // launch it
于 2022-01-14T21:20:54.390 回答