Problem Statement
What are common Stream operations and transformations? Explain map, where, transform, and listen.
Explanation
The map operation transforms each event in the stream, like stream.map((value) => value * 2) doubling each emitted value. It returns a new stream with transformed values, similar to mapping over lists but for async streams. Use map when you need to convert stream values to different types or apply transformations while maintaining the stream structure.
Where filters stream events based on a predicate, like stream.where((value) => value > 10) only emitting values greater than 10. It's the stream equivalent of filtering lists, useful for ignoring unwanted events or filtering based on conditions. Transform is more powerful, allowing complex transformations with StreamTransformer that can emit zero, one, or multiple events per input event.
Listen subscribes to a stream with a callback receiving each event, like stream.listen((value) { print(value); }). Listen returns StreamSubscription allowing you to pause, resume, or cancel the subscription. Use onError parameter for error handling, onDone for completion callback, and cancelOnError to control whether subscription cancels on first error. Always cancel subscriptions in dispose() when not using StreamBuilder.
Other useful operations include take(n) for first n events, skip(n) to skip first n events, distinct() to filter duplicates, asyncMap for async transformations, and debounce/throttle from RxDart for rate limiting. Chaining operations creates powerful stream pipelines processing data reactively. Understanding stream operations enables building complex reactive data flows handling events declaratively.
