Created
February 16, 2022 22:30
-
-
Save DewofyourYouth/22f40b2f43f64cdf4e5214b79a035f5b to your computer and use it in GitHub Desktop.
An example of a basic StreamController and StreamSubscription
This file contains 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'; | |
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