Dart by Example: Streams

  1. import 'dart:async';
  2. main() {
  3. // creates a single subscription stream
  4. new Stream.fromIterable([1, 3, 5]).listen((i) {
  5. print('s1: $i');
  6. });
  7. // New streams can created from other streams, using
  8. // using methods like where(), map(), expand(), take(), or skip()
  9. new Stream.periodic(new Duration(milliseconds: 300))
  10. .take(3)
  11. .listen((_) => print('s2: tick!'));
  12. new Stream.fromIterable([1, 2, 5]).map((n) => n * 2).listen((n) => print('s3: $n'));
  13. // Broadcast streams can be listened to by multiple consumers.
  14. var sc = new StreamController.broadcast();
  15. var broadcastStream = sc.stream;
  16. broadcastStream.listen((v) => print('s4: $v'));
  17. broadcastStream.listen((v) => print('s4: $v'));
  18. sc.add(1);
  19. sc.add(2);
  20. }
  21.  
  1. $ dart streams.dart
  2. s1: 1
  3. s3: 2
  4. s4: 1
  5. s4: 1
  6. s1: 3
  7. s3: 4
  8. s4: 2
  9. s4: 2
  10. s1: 5
  11. s3: 10
  12. s2: tick!
  13. s2: tick!
  14. s2: tick!

by @jryanio | source | license