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

Automatically connects to (and disconnects from) an IConnectableObservable depending on the number of subscribers.

function IConnectableObservable.refCount() : IObservable.<T>

Remarks

Connects to the source sequence when the first observer subscribes to the returned IObservable, and disconnects from the source sequence when the last observer is removed.

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─  ──o─────o───o──/
              │     │   │     │     │   │  │
refCount    ──o─────o───o─  ──o─────o───o──/
              │     ├┐  │     │     │   │  │
o1          ──o─────o│─ │     │     │   │  │
                    ┌┘  │     │     │   │  │
o2                 ─o───o─    │     │   │  │
                              │     │   │  │
o3                          ──o─────o───o──/
  1. o1 subscribes to the refCount sequence, causing a connection to the source sequence
  2. o2 subscribes shortly after the first value
  3. o1 cancels its subscription shortly after the second value
  4. o2 cancels its subscription shortly after the third value. As there are no subscriptions left, the subscription to the source sequence is canceled
  5. o3 subscribes to the refCount sequence, causing a new connection to the source sequence
  6. o3 never cancels it’s subscription, so the subscriptions end when the source sequence completes.

Examples

var obs : IObservable = Observable.range(1, 10, Scheduler.asynchronous)
    .publish().refCount();

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

    obs.skip(2).take(3)
        .subscribe(
            function(v:int):void { trace("Observer B: " + i.toString()); },
            function():void { trace("Observer B: Completed"); }
        );

    // Output:
    // Observer A: 0
    // Observer A: 1
    // Observer A: 2
    // Observer B: 2
    // Observer A: 3
    // Observer A: Completed
    // Observer B: 3
    // Observer B: 4
    // Observer B: Completed
Clone this wiki locally