The switch_latest operator

The switch_latest operator take a higher-order observable as input. Each time a new item is emitted on this source observable, a subscription is done on the child observable, and the existing subscription on the previous item is disposed of. The following figure shows the marble diagram of this operator:

Figure 9.14: The switch_latest operator

Its prototype is the following:

Observable.switch_latest(self)

Here is an example of the switch_latest operator:

obs1 = Subject()
obs2 = Subject()
obs3 = Subject()
higher_order = Subject()

higher_order.switch_latest().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")
)

higher_order.on_next(obs1)
obs1.on_next("1: 1")
obs1.on_next("1: 2")
higher_order.on_next(obs2)
obs1.on_next("1: 3")
obs2.on_next("2: 1")
obs2.on_next("2: 2")
higher_order.on_next(obs3)
obs2.on_next("2: 3")
obs3.on_next("3: 1")
obs3.on_next("3: 2")

In this example, three observables are created as subjects, as well as a higher-order observable (also created as a subject). The higher-order observable is subscribed after the switch_latest operator. This higher-order observable emits the three other observables. Each of these observables emits three items, but with the emission of the next observable interleaved on the higher-order observable.

This example gives the following result:

on_next 1: 1
on_next 1: 2
on_next 2: 1
on_next 2: 2
on_next 3: 1
on_next 3: 2

Only the first two items of each observable are received. This is the expected result since the third item is always emitted after another observable is emitted on the higher-order observable. So, the switch_latest operator unsubscribes the corresponding observable before the third item is emitted.

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

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