2

I am trying to use methodChannel in flutter to receive events from native Android code. But once I cancel the stream subscription I can no longer create new subscriptons even if I set the stream asBroadcastStream()

Receiver.dart

static Stream<dynamic> get accessStream {
  _stream ??= _eventChannel.receiveBroadcastStream().map<dynamic>(
    (event) {
      return MainEvent.fromMap(event);
    },
  );
  return _stream!.asBroadcastStream();
}

When trying to call the function

subs = Receiver.accessStream.listen((event) async {
          if (event != null) {
            events.add(event);
          }
        });

//After Some Time in Cancel Function
await subs.cancel()

It works for the first time but when I call the same function in app_listen.dart again. It gives the following error

[ +100 ms] E/flutter (32159): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Bad state: Stream has already been listened to.
[        ] E/flutter (32159): #0      _StreamController._subscribe (dart:async/stream_controller.dart:676:7)
[        ] E/flutter (32159): #1      _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
[        ] E/flutter (32159): #2      _StreamImpl.listen (dart:async/stream_impl.dart:473:9)
[        ] E/flutter (32159): #3      listenEvent(package:trying/util/struct/app_listen.dart:49:51)
[        ] E/flutter (32159): <asynchronous suspension>

Thanks for answering.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Just a Person
  • 1,276
  • 1
  • 5
  • 23
  • I have removed the "dart-stream" tag since it's redundant. You already have [stream], which is the correct tag. – nvoigt Jun 28 '22 at 10:52
  • 1
    "Stream has already been listened to." mean you are NOT using a broadcast stream. This is a dart error when you use a single subscription stream and listen more than once, so I think it's a bug in your code. Since you did not provide a minimal example (a project that can be run and reproduce the bug), no one can tell what's wrong. Please try to debug your code. – dante Jul 02 '22 at 04:52
  • @dante I have opened an issue in flutter and have provided my code there. Here is the link: https://github.com/flutter/flutter/issues/106927#issuecomment-1172315570 – Just a Person Jul 02 '22 at 09:09
  • @JustaPerson I know, I came here from the issue. You did not provide a runnable project, how can Flutter team reproduce the error with these files? And as I said, the error is clear, did you try to debug your code? – dante Jul 02 '22 at 16:13

1 Answers1

0

I have solved the issue by just removing the ??= and replacing it with = in Receiver.dart

Just a Person
  • 1,276
  • 1
  • 5
  • 23