🧑🎓 tltr
|
|
Print is executed multiple times till the first value that matches both filter conditions is found.
❓Question
🕵️♂️ Explanation
Let’s simplify it
|
|
This won’t do anything because there is no terminal operation which triggers the reading from the source stream.
By adding the peek
, which is an intermediate operation, the behaviour won’t change.
|
|
This findFirst
(terminal operation) evaluates the pipeline.
|
|
During the evaluation, the sinks are wrapped (combined) into one Sink. As a result, we get:
peek
Sinkfilter A
Sinkfilter B
SinkfindFirst
Sink
While the sink is not cancelled (in our case findFirst has no value) and there is an element in the stream, the pipeline will try to advance, fetch the next element and pass it to the wrapped sink as above (top-down)
✅ Walkthrough
So we will have something like this (since the stream is not empty):
The stream: 1 2 3 4 5 6 7 8 9
1
is passed topeek
sinkpeek
is executed,1
is printed1
passed tofilter A
sinkfilter A
is executed,false
is returned(1>2)
, the sink is not cancelled, continue the while
2
is fetched and passed topeek
sinkpeek
is executed,2
is printed2
passed tofilter A
sinkfilter A
is executed,false
is returned(2>2)
, the sink is not cancelled, continue the while
3
is fetched and passed topeek
sinkpeek
is executed,3
is printed3
passed tofilter A
sinkfilter A
is executed,true
is returned(3>2)
3
passed tofilter B
sinkfilter B
is executed,false
is returned(3>3)
, the sink is not cancelled, continue the while
4
is fetched and passed topeek
sinkpeek
is executed,4
is printed4
passed tofilter A
sinkfilter A
is executed,true
is returned(4>2)
4
passed tofilter B
sinkfilter B
is executed,true
is returned(4>3)
4
passed tofindFirst
sink- saves the value inside the
findFirst
which means the sink is cancelled, while interrupted
- saves the value inside the
4
returned
Another Example
Let’s move the peek
before the findFirst
. Almost the same code, and different output
Output:
|
|
The sink:
filter A
Sinkfilter B
Sinkpeek
SinkfindFirst
Sink
✅ Walkthrough
So we will have something like this:
The stream: 1 2 3 4 5 6 7 8 9
1
is passed tofilter A
sinkfilter A
is executed,false
is returned(1>2)
, the sink is not cancelled, continue the while
2
is fetched and passed tofilter A
sinkfilter A
is executed,false
is returned(2>2)
, the sink is not cancelled, continue the while
3
is fetched and passed tofilter A
sinkfilter A
is executed,true
is returned(3>2)
3
passed tofilter B
sinkfilter B
is executed,false
is returned(3>3)
, the sink is not cancelled, continue the while
4
is fetched and passed tofilter A
sinkfilter A
is executed,true
is returned(4>2)
4
passed tofilter B
sinkfilter B
is executed,true
is returned(4>3)
4
is passed topeek
sink4
is printed
4
is passed tofindFirst
sink- saves the value inside the
findFirst
which means the sink is cancelled, while interrupted
- saves the value inside the
4
returned