Streams

Basics of Streams

import 'dart:async';

void main() {
  // Streams
  var numberStream = NumberGenerator().stream;

  numberStream.listen((data) {
    print(data);
  });
}

class NumberGenerator {
  NumberGenerator() {
    Timer.periodic(Duration(seconds: 1), (t) {
      controller.sink.add(count);

      count++;
    });
  }

  var count = 1;

  final controller = StreamController<int>();

  Stream<int> get stream => controller.stream;
}


Stream emits an asynchronous sequence of data.

Types of Stream

There are two types of streams in dart :-

// This will show an error
import 'dart:async';

void main() {
  // Streams
  var numberStream = NumberGenerator().stream;

  final subscription1 = numberStream.listen((data) {
    print(data);
  });

  final subscription2 = numberStream.listen((data) {
    print(data);
  });
}

class NumberGenerator {
  NumberGenerator() {
    Timer.periodic(Duration(seconds: 1), (t) {
      controller.sink.add(count);

      count++;
    });
  }

  var count = 1;

  final controller = StreamController<int>();

  Stream<int> get stream => controller.stream;
}

Error Handling in Stream

import 'dart:async';

void main() {
  // Streams
  var numberStream = NumberGenerator().stream;

  final subscription1 = numberStream.listen((data) {
    print(data);
  }, onError: (err) {
    //logic for error handling
    print("$err, Error detected !");
  }, cancelOnError: true);
}

class NumberGenerator {
  NumberGenerator() {
    Timer.periodic(Duration(seconds: 1), (t) {
      if (count == 5) {
        controller.sink.addError("Error !!!!");
      }
      controller.sink.add(count);

      count++;
    });
  }

  var count = 1;

  final controller = StreamController<int>();

  Stream<int> get stream => controller.stream;
}

Manipulating Streams

import 'dart:async';

void main() {
  // Streams
  var numberStream = NumberGenerator().stream;

  final subscription1 =
      numberStream.map((i) => i * 3).where((i) => i % 2 == 0).listen((data) {
    print(data);
  });
}

class NumberGenerator {
  NumberGenerator() {
    Timer.periodic(Duration(seconds: 1), (t) {
      controller.sink.add(count);

      count++;
    });
  }

  var count = 1;

  final controller = StreamController<int>();

  Stream<int> get stream => controller.stream;
}

Creating Streams

If you want to explore more about Streams : -

Last updated