Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sequential read issue #308

Open
vd3d opened this issue Dec 21, 2023 · 1 comment
Open

Sequential read issue #308

vd3d opened this issue Dec 21, 2023 · 1 comment

Comments

@vd3d
Copy link

vd3d commented Dec 21, 2023

Hi,

I try to have a sequential read of every message, because I have a protocol to follow, it is in 3 steps:

  • connect
  • auth
  • subscribe

And so I wish to:

  • connect + read the connection response
  • send an "auth" message + read the auth response
  • subscribe + listen to all the other messages

Here is what I tried:

WebSocketChannel channel = WebSocketChannel.connect(Uri.parse(...));
dynamic connectionResponse = await channel.stream.last;
_handleStreamError(jsonDecode(connectionResponse));

String authPayload = '{"action": "auth", "key": "' + Secrets.alpaca.OAuthClientId + '", "secret": "' + Secrets.alpaca.OAuthClientSecret + '"}';
channel.sink.add(authPayload);
dynamic authResponse = await channel.stream.last;
_handleStreamError(jsonDecode(authResponse));

But I got an exception at the last 'channel.stream.last' : Unhandled Exception: Bad state: Stream has already been listened to

Any idea why, and how to manage this ?

Thanks

@KammererTob
Copy link

The underyling Stream of the WebSocketChannel is a single-subscription stream. Meaning it can only be listened to once. By using stream.last twice, you try to listen to it twice, which isn't allowed. Here is an excerpt from the documentation:

A single-subscription stream allows only a single listener during the whole lifetime of the stream. It doesn't start generating events until it has a listener, and it stops sending events when the listener is unsubscribed, even if the source of events could still provide more. The stream created by an async* function is a single-subscription stream, but each call to the function creates a new such stream.

Listening twice on a single-subscription stream is not allowed, even after the first subscription has been canceled.

https://api.flutter.dev/flutter/dart-async/Stream-class.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants