concept ConnectableObservable in category .net

appears as: ConnectableObservable
Rx.NET in Action

This is an excerpt from Manning's book Rx.NET in Action.

This small application creates a cold observable that emits five notifications, one every second. The application then makes the observable hot by converting it to a ConnectableObservable (more on that in a moment) and connects it to the source observable (by calling the Connect operator) after two observers subscribe. Then, after another 2 seconds, it subscribes another observer.

Both Publish and PublishLast are good for all of the common scenarios in which you need to heat a cold observable. But if you need more control or need to enforce policies on an internal subject used inside ConnectableObservable (for example, setting its buffer size and other configurations), then you need to use the Multicast operator. Multicast lets you pass the pending subject inside the Connectable-Observable

IConnectableObservable<TResult> Multicast<TSource, TResult>(
     this IObservable<TSource> source,
     ISubject<TSource, TResult> subject)

Multicast is a powerful low-level operator that’s used to create other operators. All the Publish versions use Multicast in their implementations. For example, this implementation from the Rx source code for the Publish overload creates a Behavior-Subject for ConnectableObservable:

virtual IConnectableObservable<TSource> Publish<TSource>(
     IObservable<TSource> source,
     TSource initialValue)

{
    return source.Multicast(new BehaviorSubject<TSource>(initialValue));
}

As explained earlier, this Publish overload creates a ConnectableObservable. Every observer that subscribes to it, after its Connect method is called, will receive the last value emitted from the source observable or the initial value, if no notification was yet emitted. The implementation shows that in order to provide this behavior, Behavior-Subject is used as the underlying subject passed to the Multicast operator.

You can reconnect ConnectableObservable at any time. Doing so will cause the subscribed observers to see the notifications again. Reconnecting might be useful when you want to keep the observers but need to change the original source of the observable pipeline. For example, if the source observable is a chat server, and you know that server needs to be replaced, you can reconnect, which will cause the new server to be picked up again.

Listing 7.9. Reconnecting ConnectableObservable

The Publish operator creates a ConnectableObservable wrapper around the source observable. This is a required step for allowing multicasting of the observable notifications. The Publish operator has a few overloads, so let’s examine those one by one.