Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a Stream when using Stream.periodic?

Tags:

dart

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;
  }
}
like image 717
inspirnathan Avatar asked Jul 29 '18 17:07

inspirnathan


People also ask

How do you use the periodic timer in flutter?

Execute Periodically in Flutterperiodic(Duration(seconds: 1), (timer) { setState(() { greeting = "After Some time ${DateTime. now(). second}"; }); }); This will set the value to the greeting variable in every 1 second.

What is stream subscription in flutter?

The subscription provides events to the listener, and holds the callbacks used to handle the events. The subscription can also be used to unsubscribe from the events, or to temporarily pause the events from the stream. Example: final stream = Stream.

What is periodic stream?

The Stream. periodic constructor, as its name suggests, is utilized to make a stream that communicates events more than once at period intervals. The event esteems are computed by invoking computation .

How do I cancel stream periodic flutter?

If you want to use it for example in a Flutter widget only while it is shown, you can unsubscribe from it in dispose() . For this you need to use var sub = newsstream. listen(...); instead of map(...) , so that you then can call sub.


1 Answers

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);
  });
like image 132
Günter Zöchbauer Avatar answered Oct 20 '22 23:10

Günter Zöchbauer