The window operator is similar to the buffer operator, except that it emits a higher-order observable instead of emitting list items. Its marble diagram is shown in the following figure:
The prototype of the window operator is the following:
Observable.window(self, window_openings=None,
window_closing_selector=None)
The two parameters are similar to the ones of the buffer operator. The window_opening parameter is an observable that emits items each time a new window must be created. The window_closing_selector is a function that returns an observable that completes when the current window must end.
This operator can be used in the following way:
def wrap_items(i):
return i.map(lambda j: 'obs {}: {}'.format(i, j))
numbers = Subject()
windows = Subject()
numbers.window(windows).flat_map(wrap_items).subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)
numbers.on_next(1)
numbers.on_next(2)
windows.on_next(True)
numbers.on_next(3)
numbers.on_next(4)
numbers.on_next(5)
windows.on_next(True)
This example is very similar to the first example of the buffer operator. The main difference is that the result of the window operator goes through the flat_map operator to serialize each item. Each item is mapped to a string containing the reference of the observable window. This gives the following result:
on_next obs <0x105ee6a58>: 1 on_next obs <0x105ee6a58>: 2 on_next obs <0x105ee6da0>: 3 on_next obs <0x105ee6da0>: 4 on_next obs <0x105ee6da0>: 5
The first two items are emitted on the same observable, and the last three items are emitted on another observable.