fbpEnsureDeviceIsConnected method
Implementation
Future<T> fbpEnsureDeviceIsConnected(BluetoothDevice device, String function) {
// Create a completer to represent the result of this extended Future.
var completer = Completer<T>();
// disconnection listener.
var subscription = device.connectionState.listen((event) {
if (event == BluetoothConnectionState.disconnected) {
if (!completer.isCompleted) {
completer.completeError(FlutterBluePlusException(
ErrorPlatform.fbp, function, FbpErrorCode.deviceIsDisconnected.index, "Device is disconnected"));
}
}
});
// When the original future completes
// complete our completer and cancel the subscription.
then((value) {
if (!completer.isCompleted) {
subscription.cancel();
completer.complete(value);
}
}).catchError((error) {
if (!completer.isCompleted) {
subscription.cancel();
completer.completeError(error);
}
});
return completer.future;
}