Skip to content
richardszalay edited this page May 20, 2011 · 9 revisions

Creates a connectable sequence that can be shared by multiple observers

function publish() : IConnectableObservable.<T>

Remarks

A connectable observable allows a single source subscription to be shared by multiple observers. Subscribing to the IConnectableObservable returned by publish does not subscribe to the source sequence. Instead, IConnectableObservable.connect() must be called. Once a connection is established, any messages (onNext, onCompleted, onError) received from the source sequence will be sent to all the observers.

Conversely, unsubscribing from a IConnectableObservable does not unsubscribe from the source sequence. Instead the ICancelable returned by IConnectableObservable.connect() must be canceled in order to cancel the source subscription.

To automatically subscribe/unsubscribe from the source depending on the number of subscribers, see refCount.

The sequence completes with the source sequence completes.

The sequence errors with the source sequence errors

Marble Diagrams

source   = a cold observable
publish  = the publish sequence (when connected)
o1,o2,o3 = observers

source      ──o─────o───o──/
              │     │   │
publish     ──o─────o───o──/
              │     ├┐  ├┐
o1      ──────o─────o│──o│─/
                    ┌┘  ┌┘
o2                 ─o───o──/

o3                           ────────────</pre>

o1 subscribes to the published sequence before it has been connected and so receives all the live events.
o2 subscribes to the published sequence after it has been connected and so receives all events that happen afterward
o3 subscribes to the published sequence after the source sequences has completed and so never receives any events

Examples

var obs : IConnectableObservable = Observable.interval(2000).take(3).publish();

    obs.subscribe(
        function(v:int):void { trace("Observer A: " + i.toString()); },
        function():void { trace("Observer A: Completed"); }
    );

    // After 3 seconds
    obs.subscribe(
        function(v:int):void { trace("Observer B: " + i.toString()); },
        function():void { trace("Observer B: Completed"); }
    );

    // After 6 seconds
    obs.subscribe(
        function(v:int):void { trace("Observer C: " + i.toString()); },
        function():void { trace("Observer C: Completed"); }
    );

    // Output:
    // Observer A: 0
    // Observer A: 1
    // Observer A: Completed
    // Observer B: 1
    // Observer B: Completed