onEach method
Invokes the specified action for each element in the iterable and returns
a new lazy iterable that yields the same elements.
This method is useful for performing a side effect (such as printing or logging) for each element in the iterable while maintaining the original order of elements.
-
Parameters:
- action: The function to be invoked for each element in the iterable.
-
Returns: A new lazy Iterable that yields the same elements as the original iterable, but with the specified
actioninvoked for each element. -
Example:
Iterable<int> numbers = [1, 2, 3, 4, 5]; Iterable<int> squaredNumbers = numbers.onEach((element) { print('Processing: $element'); }).map((element) => element * element);
Note:
This method does not modify the original iterable. It creates a new lazy
iterable that applies the specified action to each element and yields the
same elements as the original iterable.
Implementation
Iterable<T> onEach(void action(T element)) sync* {
for (var element in this) {
action(element);
yield element;
}
}