Skip to content

Instantly share code, notes, and snippets.

@AlexVegner
Last active January 24, 2020 19:00
Show Gist options
  • Save AlexVegner/8d2c949655c37fd6b19c1936a8f46400 to your computer and use it in GitHub Desktop.
Save AlexVegner/8d2c949655c37fd6b19c1936a8f46400 to your computer and use it in GitHub Desktop.
dart_stream.dart
import 'dart:async';
main() async {
await periodicStreamSample();
// await streamControllerSample();
// await streamControllerWithPeriodicEmitsAndWaiterSample();
}
Future<void> periodicStreamSample() async {
final subscription = Stream.periodic(
Duration(seconds: 1),
(value) => value,
).listen(print);
await Future.delayed(Duration(seconds: 10));
subscription.cancel();
}
Future<void> streamControllerSample() async {
// StreamController has 1 listener
final streamController = StreamController();
// Accessing the stream and listening for data event
final streamControllerSubscription = streamController.stream.listen((data) {
print('Got eem! $data');
}, onDone: () {
print("Task Done");
}, onError: (error) {
print("Some Error");
});
streamController.sink.add('event1');
streamController.sink.add('event2');
streamController.sink.add('event3');
streamController.sink.add('event4');
await Future.delayed(Duration(seconds: 1));
streamControllerSubscription.cancel();
streamController.close();
}
Future<void> streamControllerWithPeriodicEmitsAndWaiterSample() async {
final streamController = StreamController<String>.broadcast();
// Accessing the stream and listening for data event
final streamControllerSubscription = streamController.stream.listen((data) {
print('Got eem! $data');
});
final subscription = Stream.periodic(
Duration(seconds: 1),
(value) => value,
).listen((data) => streamController.sink.add('event$data'));
await streamController.stream.firstWhere((event) => event == 'event3',
orElse: () => 'event not found');
subscription.cancel();
streamControllerSubscription.cancel();
print('cancel subscriptions');
streamController.close();
print('close streem');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment