The join operator

The join operator combines the items emitted by two observables when they are emitted within a specified time window. The join operator is very similar to the combine_latest operator, but with additional time constraints. The following figure shows the marble diagram of the join operator:

Figure 9.13: The join operator

Its prototype is the following:

Observable.join(self, right, 
left_duration_selector,
right_duration_selector,
result_selector)

Here, the right parameter is the second observable to combine (self is referred to as the left operator). The left_duration_selector parameter is a function that returns an observable whose lifetime corresponds to the validity time of the item emitted on the left observable. This function is called each time the left observable emits an item. The right_duration_selector parameter is a function that returns an observable whose lifetime corresponds to the validity time of the item emitted on the right observable. This function is called each time the right observable emits an item.

Here is an example of this operator:

numbers1 = Subject()
numbers2 = Subject()

numbers1.join(numbers2,
lambda i: Observable.just(True).delay(200),
lambda i: Observable.just(True).delay(300),
lambda i, j: i + j)
.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")
)

numbers1.on_next(0)
numbers2.on_next(2)
numbers1.on_next(1)
time.sleep(0.4)
numbers1.on_next(2)
numbers2.on_next(5)
time.sleep(0.25)
numbers1.on_next(3)
numbers2.on_next(3)

The first parameter of the join operator is the number2 observable. Then, two functions are provided. These function are called each time an item is emitted on numbers1 and numbers2. They return an observable that emits only one item, but delayed. This allows us to control when the observable will complete. In practice, the first lambda returns an observable that completes after 200 milliseconds and the second lambda returns an observable that completes after 300 milliseconds. After that, items on both observables are emitted the same way as on the marble diagram of Figure 9.13.

This examples gives the following result:

on_next 2
on_next 3
on_next 7
on_next 8
on_next 6

This corresponds to the expected result, as shown in Figure 9.13.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108