StreamController callbacks example
import 'dart:async'; | |
void main() async { | |
final subscription = numberStreamWithController(8) | |
.listen((event) => print("received $event")); | |
await Future.delayed(Duration(seconds: 3)); | |
print("idling for 2 seconds"); | |
subscription.pause(); | |
await Future.delayed(Duration(seconds: 2)); | |
subscription.resume(); | |
await Future.delayed(Duration(seconds: 4)); | |
subscription.cancel(); | |
} | |
Stream<int> numberStreamWithController(int countTo) { | |
var controller = null; | |
Timer timer = null; | |
var counter = 0; | |
void count(_) { | |
controller.add(counter); | |
if (counter == countTo) { | |
timer.cancel(); | |
} | |
counter++; | |
} | |
void start() { | |
print("starting the Stream"); | |
timer = Timer.periodic(Duration(milliseconds: 1000), count); | |
timer.tick; | |
} | |
void pause() { | |
print("pausing the Stream"); | |
timer.cancel(); | |
} | |
void resume() { | |
print("resuming the Stream"); | |
timer = Timer.periodic(Duration(milliseconds: 1000), count); | |
timer.tick; | |
} | |
void stop() { | |
print("stopping the Stream"); | |
timer.cancel(); | |
} | |
controller = StreamController<int>( | |
onListen: start, | |
onPause: pause, | |
onResume: resume, | |
onCancel: stop); | |
return controller.stream; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment