Created
August 11, 2022 20:16
-
-
Save RileySeaburg/10e1abdb55569881841b3e913d136b26 to your computer and use it in GitHub Desktop.
Dart Streams Example with a Cake Factory
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 Cake {} | |
class Order { | |
String type; | |
Order(this.type); | |
} | |
void main() { | |
final controller = StreamController(); | |
final order = Order('chocolate'); | |
// create baker to bake the order | |
final baker = StreamTransformer.fromHandlers(handleData: (cakeType, sink) { | |
if (cakeType == 'chocolate') { | |
sink.add(Cake()); | |
} else { | |
sink.addError("I can't bake that type!"); | |
} | |
}); | |
controller.sink.add(order); | |
controller.stream | |
// create order inspector | |
// order inspector recieves an order object | |
// hands of a string to the baker. | |
// return the type of order | |
.map((order) => order.type) | |
// connect baker to stream | |
.transform(baker) | |
// add pickup office | |
// listens to any value coming out of the stream. | |
.listen((cake) => {print("Here's your $cake")}, | |
onError: (error) => {print(error)}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment