dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.06k stars 1.56k forks source link

Stream API does not document whether listeners can process events synchronously upon listen #55035

Open LewisHolliday opened 6 months ago

LewisHolliday commented 6 months ago

Whether through stream.listen or other methods of Stream, listeners should not appear to have processed events in the current microtask. At least, that's what I think the design intends.

Evidence of that can be found throughout the API docs of StreamController and SynchronousStreamController: streamController.add StreamController() StreamController-class

I do not think the invariants mentioned in those links are well defined in the Stream API documentation. Stream's class documentation's first line: "A source of asynchronous data events." might be the closest it gets.

Also, I think the docs should clarify whether listeners of a given stream may appear to process any events in a microtask where a streamSubscription.resume of said stream was called.

lrhn commented 6 months ago

Correct. No event should be fired in direct response to StreamSubscription.resume or Stream.listen. Events should be fired as if they are separate asynchronous events, coming from the microtask event queue or top-level event loop.

The SynchronousStreamController can be used to break this contract. If it does so, all bets are off on whether library operations will even work for that stream. It's unspecified behavior, basically. The synchronous controller should only be used to emit events from code that is already running as an event, which onResume and onListen are not.

It could probably be expressed more directly than it is today.