-
Notifications
You must be signed in to change notification settings - Fork 8
refCount
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>
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
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──/
- o1 subscribes to the refCount sequence, causing a connection to the source sequence
- o2 subscribes shortly after the first value
- o1 cancels its subscription shortly after the second value
- o2 cancels its subscription shortly after the third value. As there are no subscriptions left, the subscription to the source sequence is canceled
- o3 subscribes to the refCount sequence, causing a new connection to the source sequence
- o3 never cancels it’s subscription, so the subscriptions end when the source sequence completes.
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