Created
November 7, 2020 18:40
-
-
Save nsmirosh/bbf8f633465b7844ba0527e72912045f to your computer and use it in GitHub Desktop.
StreamController callbacks example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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