Skip to content

Instantly share code, notes, and snippets.

@DewofyourYouth
Created February 16, 2022 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DewofyourYouth/22f40b2f43f64cdf4e5214b79a035f5b to your computer and use it in GitHub Desktop.
Save DewofyourYouth/22f40b2f43f64cdf4e5214b79a035f5b to your computer and use it in GitHub Desktop.
An example of a basic StreamController and StreamSubscription
import 'dart:async';
class Person {
final String firstName;
final String lastName;
Person({required this.firstName, required this.lastName});
factory Person.fromMap(Map<String, dynamic> m) {
return Person(
firstName: m['firstName'] ?? "", lastName: m['lastName'] ?? "");
}
@override
String toString() {
return "Person(firstName=$firstName, lastName=$lastName)";
}
}
void main() async {
final StreamController<Map<String, dynamic>> ctrl = StreamController();
final StreamSubscription subscription = ctrl.stream.listen((data) => data,
onError: (e) => print("Error: $e"), onDone: () => print('Yay!!!'));
ctrl.sink.add({'firstName': "Joe", 'lastName': "Shmoe"});
ctrl.sink.add({'firstName': "Vivian", "lastName": "Fox"});
ctrl.sink.add({'firstName': "Gary", "lastName": "Larson"});
ctrl.sink.add({"firstName": "Elijah"});
ctrl.sink.addError('Yer mum!');
ctrl.sink.add({"name": "Drew Barrymore"});
subscription.onData((data) {
if (validateMap(data)) print(Person.fromMap(data));
});
subscription.onDone(() => print("All done!"));
await ctrl.close();
}
bool validateMap(Map m) {
return m.keys.contains('firstName') && m.keys.contains('lastName');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment