I have a class that receives data from the device sensors. I've wrapped the callback inside a callbackFlow in order to get a Flow.
private var sensorFlow: Flow<AccelerationState> = callbackFlow {
val listener: SensorEventListener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent?) {
...
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
...
}
}
sensorManager.registerListener(listener, accelSensor, SensorManager.SENSOR_DELAY_NORMAL)
awaitClose() {
sensorManager.unregisterListener(listener, accelSensor)
}
}
Ideally want to expose a StateFlow so I've done this:
sensorFlow.stateIn(
scope = scope,
started = WhileSubscribed(5000),
initialValue = AccelerationState(0,0,0))
I want to be able to pause/resume the sensor readings which I would normally do by registering/unregistering the listener. My understanding is that I have to stop listening to the flow and then restart it again if I want to have that effect.
I've tried using takeWhile { isGathering } but after the Flow is killed it can't be restarted again. And redeclaring the StateFlow does nothing as the rest of the app has the previous reference stored.
How can I expose a StateFlow but be able to change the underlying Flow from which it's created?
Edit: The StateFlow is then simply referenced in a ViewModel and can then be accessed by the View:
val sensorStateFlow = sensorDataRepository.sensorStateFlow