Operators – publish and connect

The publish operator converts an observable to a connectable observable. A connectable observable does not start to emit items when an observer subscribes to it, but when its connect method is called. The combination of publish and connect allows us to make an observable hot, but also to ensure that several observers will receive the whole sequence of items. The following figure shows its marble diagram:

Figure 4.14: The publish operator

The prototypes of the publish and connect operators are as follows:

Observable.publish(self)
ConnectableObservable.connect(self)

Both of the operators are methods, but connect is a method of the ConnectableObservable class. The following example shows how the publish and connect operators modify the behavior of an observable:

numbers = Observable.from_([1,2,3])
pub_numbers = numbers.publish()
pub_numbers.connect()

pub_numbers.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

pub_numbers.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

Executing the preceding code provides the following result:

completed
completed

No items were received by either subscriptions! This is the expected behavior; the numbers observable is published and connected before the subscriptions. As explained previously, the subscription to the observable occurs when connect is called, not when observers subscribe to the ConnectableObservable. In this case, the three numbers are emitted before any observer is subscribed to the pub_numbers observable. When they subscribe later, the observable is already completed. If the call to connect is moved between the two subscriptions, the code sample provides the following output:

item: 1
item: 2
item: 3
completed
completed

In this case, the first subscription occurred before connecting to the ConnectableObservable class. So, when the observable started to emit items, the first subscription received them. The second subscription still missed all of them, because the observable completed previously. Finally, if the call to connect is moved to the end of the code, the output will be as follows:

item: 1
item: 1
item: 2
item: 2
item: 3
item: 3
completed
completed

Both of the subscriptions received each item. Their print statements are interleaved because all of the observers are notified of an item before the next 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
3.143.5.15