You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Part 4 - Concurrency/3. Sequences of coincidence.md
+40Lines changed: 40 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -77,6 +77,25 @@ You can contruct windows that overlap or skip elements, just like you would with
77
77
publicfinalObservable<Observable<T>> window(long timespan, long timeshift, java.util.concurrent.TimeUnit unit)
78
78
```
79
79
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
+
80
99
### Window with signal
81
100
82
101
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
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.
0 commit comments