inspirnathan
inspirnathan

Reputation: 381

How to cancel a Stream when using Stream.periodic?

I'm having trouble canceling a stream that is created using the Stream.periodic constructor. Below is my attempt at canceling the stream. However, I'm having a hard time extracting out the 'count' variable from the internal scope. Therefore, I can't cancel the subscription.

import 'dart:async';

void main() {
  int count = 0;
  final Stream newsStream = new Stream.periodic(Duration(seconds: 2), (_) {
    return _;
  });

  StreamSubscription mySubscribedStream = newsStream.map((e) {
    count = e;
    print(count);
    return 'stuff $e';
  }).listen((e) {
    print(e);
  });

  // count = 0 here because count is scoped inside mySubscribedStream
  // How do I extract out 'count', so I can cancel the stream?
  if (count > 5) {
    mySubscribedStream.cancel();
    mySubscribedStream = null;
  }
}

Upvotes: 21

Views: 9530

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657178

I'd rather use take(5) instead of checking > 5 and then cancel

final Stream newsStream = new Stream.periodic(Duration(seconds: 2), (_)  => count++);

newsStream.map((e) {
    count = e;
    print(count);
    return 'stuff $e';
  }).take(5).forEach((e) {
    print(e);
  });

Upvotes: 4

Related Questions