finalize()¶
Iterates over the given stream source and yields its items. When iteration completes or an exception occurs, the finalization function is invoked.
This is equivalent to executing the iteration inside a try/finally block.
If iteration of the stream source ends prematurely (for example, via a break
statement), the finalization function is invoked when the operator instance
is garbage-collected.
- class RunOpenCode\Component\Dataset\Operator\Finalize¶
- __construct(iterable<TKey, TValue> $source, callable(): void $finalizer)¶
- Parameters:
$source –
iterable<TKey, TValue>Stream source to iterate over.$finalizer –
callable(): voidUser defined callable to invoke when iterator is depleted, or exception is thrown, or operator instance is garbage collected.
- getIterator()¶
- Returns:
\Traversable<TKey, TValue>Items from the stream source.
Use cases¶
Use this operator when you want to express finalization logic in a declarative manner.
Example¶
Finalization logic for stream processing may be provided by wrapping stream processing with try/finally block:
1<?php
2
3try {
4 new Stream(...)
5 ->filter(...)
6 ->map(...)
7 ->tap(...);
8} finally {
9 // Finalization logic...
10}
However, with this operator, same result can be achieved in declarative manner:
1<?php
2
3new Stream(...)
4 ->filter(...)
5 ->map(...)
6 ->tap(...)
7 ->finalize(function(): void {
8 // Finalization logic
9 });