I basically know how to use them; for instance listening to the onClick Stream of an Element.
But, how do you set up your own Streams?
Broadcast streams: A broadcast stream allows any number of listeners. It fires when its events are ready, whether there are listeners or not. To create a broadcast stream, you simply call asBroadcastStream() on an existing single subscription stream. Syntax: final broadcastStream = singleStream.
Streams provide an asynchronous sequence of data. Data sequences include user-generated events and data read from files. You can process a stream using either await for or listen() from the Stream API. Streams provide a way to respond to errors. There are two kinds of streams: single subscription or broadcast.
add("Data!"); With a StreamController instance, you can access a stream to listen for and react to data events using the Stream instance's listen() method, and you can access a sink to add new data events to the stream using the add() method of EventSink.
Here's a complete working example:
import 'dart:async'; import 'dart:io'; class Application { Stream onExit; Application() { // Create a stream controller and assign its stream to "onExit". var controller = new StreamController(); onExit = controller.stream; // Create some class that uses our stream. new UserOfStream(this); // Whenever we exit the application, notify everyone about it first. controller.add('we are shutting down!'); exit(0); } } class UserOfStream { UserOfStream(app) { app.onExit.listen((String message) => print(message)); } } main() => new Application();
You can also do cool things like check if there are subscribers with controller.hasListener
or you can signal an error. Be sure to check the API documentation on StreamController
.
You can use new StreamController.broadcast()
for allowing multiple listeners.
Here's a simple way to create a stream (great snippet for copy-pasters):
class Something { StreamController _onExitController = new StreamController.broadcast(); Stream get onExit => _onExitController.stream; }
Then the class can just access _onExitController
to control the stream (to for example .add()
).
In addition to StreamController
you can instantiate a Stream
directly with one of its named constructors:
Stream.fromFuture()
Returns a stream that fires one event (whatever the Future
completes to.)
Stream.fromIterable()
Returns a stream that converts the Iterable
elements to a sequence of events.
Stream.periodic()
Returns a stream that fires a computed event periodically.
This is very handy as you can write code that expects to consume a stream, but you have multiple choices as to how to feed events to that class. For example: Stream.fromIterable()
could be used in a unit test to fire a known sequence of events to a class that otherwise normally would be fed data events read from a file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With