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;
}
}
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.
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.
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 .
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.
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);
});
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