fbpEnsureDeviceIsConnected method

Future<T> fbpEnsureDeviceIsConnected(
  1. BluetoothDevice device,
  2. String function
)

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;
}