observeConnectionState method
Future<Stream<BleConnectionState> >
observeConnectionState({
- required String deviceAddress,
override
Observes connection state changes for a device without initiating a connection.
Unlike connect, this method does not initiate a connection attempt. It only sets up monitoring for connection state changes for a device that has been previously discovered or connected. This is useful for:
- Monitoring devices that may reconnect automatically
- Observing connection changes initiated by other apps or the system
- Tracking connection state without actively managing the connection
The device must have been discovered through scanning or previously connected before this method can monitor its state.
Returns a Stream of BleConnectionState that emits whenever the connection state changes for the specified device.
Implementation
@override
Future<Stream<BleConnectionState>> observeConnectionState({
required String deviceAddress,
}) async {
// For the fake implementation, create or reuse a stream controller
// but don't initiate a connection
final StreamController<BleConnectionState> controller =
_connectionControllers.putIfAbsent(
deviceAddress,
StreamController<BleConnectionState>.broadcast,
);
// Emit the current state after a microtask delay to allow listeners to be set up
// This simulates the async nature of the platform channel
final BleConnectionState currentState =
_connectionStates[deviceAddress] ?? BleConnectionState.disconnected;
Future<void>.delayed(const Duration(milliseconds: 1), () {
if (!controller.isClosed) {
controller.add(currentState);
}
});
return controller.stream;
}