dart event loop, futures and streams
A Future represents a single value that might end up as data, error, or
incomplete. For each of these states we wire up different handlers. For data
we use the then
method on the Future, which takes a function (data) {}
,
where data
is the input that enters the event loop asynchronously.
Pay special attention here.
Incase it wasn't a regular data like 5, but an error, we could setup the handler like this:
Here, even though .catchError
was invoked on the .then
of the Future,
both are meant to handle the same Future. But if instead of .catchError
we used a .then
we are working on a different Future: the one returned by
the handler of the previous Future. For example:
The second then
is a handler for a new FuturecatchError
worked on the First future had the value been an error.
The event loop really runs the show. All streams let the data in into the event loop, where handlers are set to work with it synchronously (unless Isolates are explictly used). Note: What's asynchronous here is just delivery of events originating from other threads into the event loop thread/the main thread. So its asynchronous delivery and synchronous handling.
Let's start with the basic stdin. stdin (like stdout and stderr) is managed by the kernel. You don't get the typical .close() method for this stream. The closing of this stream is done by the kernel when the process finishes.