Question

Why dart calls my function "aFunction" after Step2? If I execute this code this text below in console:

Step2 Step1

My code:

void main()
{
 ...
 stream.listen(aFunction);
 print("Step2");
 ...
}

void aFunction()
{
 print("Step1");
}

Thanks for help.

Was it helpful?

Solution

One of the few promises that a Dart Stream makes is that it generates no events in response to a listen call. The events may come at a later time, but the code calling 'listen' is allowed to continue, and complete, before the first event is fired. We originally allowed streams to fire immediately on a listen, but when we tried to program with that, it was completely impossible to control in practice.

The same is true for listening on a future, for example with 'then'. The callback will never come immediately.

Events should generally act as if they were fired by the top-level event loop, so the event handler doesn't have to worry if other code is running - other code that might not be reentrant.

That is not always the case in practice. One event handler may trigger other events through a synchronous stream controller, effectively turning one event into anoter. That requires the event handler to know what it is doing. Synchronous controllers are intended for internal use inside, e.g., a stream transformer, and using a synchronous stream controller isn't recommended in general.

So, no, you can't have the listen call immediately trigger the callback.

OTHER TIPS

You can listen to a stream synchronously if you created a StreamController with the sync option enabled. Here is an example to get what you describe:

var controller = new StreamController<String>(sync: true);
var stream = controller.stream.asBroadcastStream();
stream.listen((text) => print(text));
controller.add("Step1");
print("Step2");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top