Skip to content

Commit

Permalink
Modified example to keep a list of ValueChanged subscriptions. #44
Browse files Browse the repository at this point in the history
  • Loading branch information
pauldemarco committed Mar 9, 2018
1 parent 7d6eff1 commit 69d9508
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class _FlutterBlueAppState extends State<FlutterBlueApp> {
StreamSubscription deviceConnection;
StreamSubscription deviceStateSubscription;
List<BluetoothService> services = new List();
StreamSubscription<List<int>> valueChangedSubscription;
Map<Guid, StreamSubscription> valueChangedSubscriptions;
BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;

@override
Expand Down Expand Up @@ -124,6 +124,9 @@ class _FlutterBlueAppState extends State<FlutterBlueApp> {
}

_disconnect() {
// Remove all value changed listeners
valueChangedSubscriptions.forEach((uuid, sub) => sub.cancel());
valueChangedSubscriptions.clear();
deviceStateSubscription?.cancel();
deviceStateSubscription = null;
deviceConnection?.cancel();
Expand Down Expand Up @@ -157,13 +160,18 @@ class _FlutterBlueAppState extends State<FlutterBlueApp> {
_setNotification(BluetoothCharacteristic c) async {
if (c.isNotifying) {
await device.setNotifyValue(c, false);
// Cancel subscription
valueChangedSubscriptions[c.uuid]?.cancel();
valueChangedSubscriptions.remove(c.uuid);
} else {
await device.setNotifyValue(c, true);
valueChangedSubscription = device.onValueChanged(c).listen((d) {
final sub = device.onValueChanged(c).listen((d) {
setState(() {
print('onValueChanged $d');
});
});
// Add to map
valueChangedSubscriptions[c.uuid] = sub;
}
setState(() {});
}
Expand Down

0 comments on commit 69d9508

Please sign in to comment.