From 76aed89cb293607b054bcbd85b5c35731caeeec6 Mon Sep 17 00:00:00 2001 From: MrCsabaToth Date: Sun, 26 Jun 2022 22:39:33 -0700 Subject: [PATCH] Fix https://github.com/boskokg/flutter_blue_plus/issues/13 (orig https://github.com/pauldemarco/flutter_blue/issues/608) by variation of https://github.com/pauldemarco/flutter_blue/pull/609 (or https://github.com/w-rui/flutter_blue/commit/bac3b164edf8023f36f020f6e2ccd5a097cfdb50) --- lib/src/flutter_blue_plus.dart | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/src/flutter_blue_plus.dart b/lib/src/flutter_blue_plus.dart index a063e25d..c7775647 100644 --- a/lib/src/flutter_blue_plus.dart +++ b/lib/src/flutter_blue_plus.dart @@ -14,6 +14,13 @@ class FlutterBluePlus { Stream get _methodStream => _methodStreamController .stream; // Used internally to dispatch methods from platform. + /// Fix for issue https://github.com/pauldemarco/flutter_blue/issues/608 + /// 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? _stateStream; + /// Singleton boilerplate FlutterBluePlus._() { _channel.setMethodCallHandler((MethodCall call) async { @@ -83,10 +90,12 @@ 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]); + + yield* _stateStream!; } /// Retrieve a list of connected devices