@@ -741,6 +741,9 @@ class SplitioWeb extends SplitioPlatform {
741741 _factory.UserConsent .setStatus (enabled.toJS);
742742 }
743743
744+ // To ensure the public `onXXX` callbacks and `whenXXX` methods work correctly,
745+ // the `onXXX` method implementations always return a Future or Stream that waits for the client to be initialized.
746+
744747 @override
745748 Future <void >? onReady (
746749 {required String matchingKey, required String ? bucketingKey}) async {
@@ -813,31 +816,37 @@ class SplitioWeb extends SplitioPlatform {
813816 @override
814817 Stream <void >? onUpdated (
815818 {required String matchingKey, required String ? bucketingKey}) {
816- final client = _clients[buildKeyString (matchingKey, bucketingKey)];
817-
818- if (client == null ) {
819- return null ;
820- }
819+ // To ensure the public `onUpdated` callback and `whenUpdated` method work correctly,
820+ // this method always return a stream, and the StreamController callbacks
821+ // are async to wait for the client to be initialized.
821822
822823 late final StreamController <void > controller;
823824 final JSFunction jsCallback = (() {
824825 if (! controller.isClosed) {
825826 controller.add (null );
826827 }
827828 }).toJS;
829+ final registerJsCallback = () async {
830+ final client = await _getClient (
831+ matchingKey: matchingKey,
832+ bucketingKey: bucketingKey,
833+ );
834+ client.on (client.Event .SDK_UPDATE , jsCallback);
835+ };
836+ final deregisterJsCallback = () async {
837+ final client = await _getClient (
838+ matchingKey: matchingKey,
839+ bucketingKey: bucketingKey,
840+ );
841+ client.off (client.Event .SDK_UPDATE , jsCallback);
842+ };
828843
829844 controller = StreamController <void >(
830- onListen: () {
831- client.on (client.Event .SDK_UPDATE , jsCallback);
832- },
833- onPause: () {
834- client.off (client.Event .SDK_UPDATE , jsCallback);
835- },
836- onResume: () {
837- client.on (client.Event .SDK_UPDATE , jsCallback);
838- },
845+ onListen: registerJsCallback,
846+ onPause: deregisterJsCallback,
847+ onResume: registerJsCallback,
839848 onCancel: () async {
840- client. off (client. Event . SDK_UPDATE , jsCallback );
849+ await deregisterJsCallback ( );
841850 if (! controller.isClosed) {
842851 await controller.close ();
843852 }
0 commit comments