Skip to content

Commit

Permalink
Fix updating the recording state to the latest running service state
Browse files Browse the repository at this point in the history
  • Loading branch information
tonelli-m committed Dec 17, 2024
1 parent efebf8e commit 4b4452f
Showing 1 changed file with 22 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
Expand Down Expand Up @@ -47,6 +48,15 @@ class AndroidMeasurementRecordingService(
*/
private var wrapper: ForegroundServiceWrapper? = null

/**
* Will take care of delivering the recording state of the latest running wrapped service,
* or false if no wrapped service is currently available.
*/
private val mergedIsRecordingFlow = MutableStateFlow(false)

private val scope = CoroutineScope(Dispatchers.Default)
private var isRecordingRedirectionJob: Job? = null

/**
* Service connection will allow us to retrieve the wrapper instance when the service is started.
*/
Expand All @@ -64,27 +74,34 @@ class AndroidMeasurementRecordingService(
wrapper = localBinder.getService()

wrapper?.innerService?.start()

isRecordingRedirectionJob = scope.launch {
// Redirect the
wrapper?.innerService?.isRecordingFlow?.collect {
mergedIsRecordingFlow.tryEmit(it)
}
}
}

/**
* Called when service is disconnected.
*/
override fun onServiceDisconnected(name: ComponentName?) {
wrapper = null
isRecordingRedirectionJob?.cancel()
mergedIsRecordingFlow.tryEmit(false)
}
}

private val _isRecordingFlow = MutableStateFlow(false)


// - MeasurementRecordingService

override val isRecording: Boolean
get() = wrapper?.innerService?.isRecording ?: false
get() = mergedIsRecordingFlow.value

// TODO: Figure out a way to always listen to the state of the last started service
override val isRecordingFlow: StateFlow<Boolean>
get() = wrapper?.innerService?.isRecordingFlow ?: _isRecordingFlow
get() = mergedIsRecordingFlow


override fun start() {
startForegroundServiceWrapper()
Expand Down

0 comments on commit 4b4452f

Please sign in to comment.