Operators – ref_count and share

There are cases wherein calling the connect method at the correct time is not easy, or is not necessary. In many cases, a cold observable can be converted to a hot observable whenever a first observer subscribes to it, as long as some subscriptions are ongoing. The ref_count operator does just that: it converts a cold observable to a hot observable as soon as a first subscription occurs. Its prototype is as follows:

ConnectableObservable.ref_count(self)

It is a method of the ConnectableObservable class. So, it must be used after a call to publish, as follows:

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

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")
)

This example is very similar to the previous one, with ref_count chained to the publish call. The result of this example is as follows:

item: 1
item: 2
item: 3
completed
completed

Only the first subscription received the items. In this case, the first subscription triggered the emission of the items, and, when the second subscription occurs, the observable has already completed. This difference between the ref_count operator and the connect operator is important to understand: the connect operator allows us to control when the observable starts to emit items, but ref_count doesn't.

Using the ref_count operator can be a little bit tedious because one has to use two operators. This can be avoided by using the share operator, which just chains a publish and ref_count call, as follows:

#pub_numbers = numbers.publish().ref_count()
pub_numbers = numbers.share()
..................Content has been hidden....................

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