Skip to content

Commit

Permalink
Fix FlutterBlue.state stream cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
boskokg committed Jul 23, 2022
1 parent 362fb16 commit 9abbd7a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* connect timeout fixed (thanks to crazy-rodney, sophisticode, SkuggaEdward, MousyBusiness and cthurston)
* Add timestamp field to ScanResult class #59 (thanks to simon-iversen)
* Add FlutterBlue.name to get the human readable device name #93 (thanks to mvo5)
* Fix bug where if there were multiple subscribers to FlutterBlue.state and one cancelled it would accidentally cancel all subscribers (thank to MacMalainey and MrCsabaToth)

## 1.1.3
* Read RSSI from a connected BLE device #1 (thanks to sophisticode)
Expand Down
13 changes: 11 additions & 2 deletions lib/src/flutter_blue_plus.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ class FlutterBluePlus {
Stream<MethodCall> get _methodStream => _methodStreamController
.stream; // Used internally to dispatch methods from platform.

/// Cached broadcast stream for FlutterBlue.state events
/// Caching this stream allows for more than one listener to subscribe
/// and unsubscribe apart from each other,
/// while allowing events to still be sent to others that are subscribed
Stream<BluetoothState>? _stateStream;

/// Singleton boilerplate
FlutterBluePlus._() {
_channel.setMethodCallHandler((MethodCall call) async {
Expand Down Expand Up @@ -87,10 +93,13 @@ class FlutterBluePlus {
.then((buffer) => protos.BluetoothState.fromBuffer(buffer))
.then((s) => BluetoothState.values[s.state.value]);

yield* _stateChannel
_stateStream ??= _stateChannel
.receiveBroadcastStream()
.map((buffer) => protos.BluetoothState.fromBuffer(buffer))
.map((s) => BluetoothState.values[s.state.value]);
.map((s) => BluetoothState.values[s.state.value])
.doOnCancel(() => _stateStream = null);

yield* _stateStream!;
}

/// Retrieve a list of connected devices
Expand Down

0 comments on commit 9abbd7a

Please sign in to comment.