X Tutup
Skip to content

Commit 67f14d9

Browse files
committed
Added window examples by time and by signal
1 parent a673bdf commit 67f14d9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Part 4 - Concurrency/3. Sequences of coincidence.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,25 @@ You can contruct windows that overlap or skip elements, just like you would with
7777
public final Observable<Observable<T>> window(long timespan, long timeshift, java.util.concurrent.TimeUnit unit)
7878
```
7979

80+
```java
81+
Observable.interval(100, TimeUnit.MILLISECONDS)
82+
.take(5)
83+
.window(250, 100, TimeUnit.MILLISECONDS)
84+
.flatMap(o -> o.toList())
85+
.subscribe(System.out::println);
86+
```
87+
Output
88+
```
89+
[0, 1]
90+
[0, 1, 2]
91+
[1, 2, 3]
92+
[2, 3, 4]
93+
[3, 4]
94+
[4]
95+
```
96+
97+
In this example, a ne window begins every 100ms and lasts 250ms. The first window opens at time 0ms and remains open long enough to catch `[0, 1]` (interval emits the first value at time 100ms). Every subsequent window remains open long enough to catch the next 3 values, except for when the values stop.
98+
8099
### Window with signal
81100

82101
Lastly, you can define windows using another observable. Every time your signaling observable emits a value, the old window closes and a new one starts.
@@ -87,6 +106,27 @@ Alternatively, to have overlapping windows, you can provide a function that uses
87106

88107
![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window2.png)
89108

109+
Here's an example with overlapping windows based on signaling observables
110+
111+
```java
112+
Observable.interval(100, TimeUnit.MILLISECONDS)
113+
.take(5)
114+
.window(
115+
Observable.interval(100, TimeUnit.MILLISECONDS),
116+
o -> Observable.timer(250, TimeUnit.MILLISECONDS))
117+
.flatMap(o -> o.toList())
118+
.subscribe(System.out::println);
119+
```
120+
Output
121+
```
122+
[1, 2]
123+
[2, 3]
124+
[3, 4]
125+
[4]
126+
[]
127+
```
128+
129+
This example is the same as the previous example: a new window opens every 100ms and lasts 250ms, with the exception that the first window starts at 100ms rather than 0ms. We see a difference in results, however. The window that begins at time 100ms does not catch the value that is emitted at 100ms, and the same goes for every other window. This happens because the `interval` event that begins the window fires just after the `interval` event that is the value. Even though the two events are simultaneous in theory, in practice there is no such guarantee.
90130

91131
## Join
92132

0 commit comments

Comments
 (0)
X Tutup