| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
#if !NO_PERF |
| 4 |
using System; |
| 5 |
using System.Reactive.Disposables; |
| 6 |
using System.Reactive.Subjects; |
| 7 |
|
| 8 |
namespace System.Reactive.Linq.ObservableImpl |
| 9 |
{ |
| 10 |
class RefCount<TSource> : Producer<TSource> |
| 11 |
{ |
| 12 |
private readonly IConnectableObservable<TSource> _source; |
| 13 |
|
| 14 |
private readonly object _gate; |
| 15 |
private int _count; |
| 16 |
private IDisposable _connectableSubscription; |
| 17 |
|
| 18 |
public RefCount(IConnectableObservable<TSource> source) |
| 19 |
{ |
| 20 |
_source = source; |
| 21 |
_gate = new object(); |
| 22 |
_count = 0; |
| 23 |
_connectableSubscription = default(IDisposable); |
| 24 |
} |
| 25 |
|
| 26 |
protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink) |
| 27 |
{ |
| 28 |
var sink = new _(this, observer, cancel); |
| 29 |
setSink(sink); |
| 30 |
return sink.Run(); |
| 31 |
} |
| 32 |
|
| 33 |
class _ : Sink<TSource>, IObserver<TSource> |
| 34 |
{ |
| 35 |
private readonly RefCount<TSource> _parent; |
| 36 |
|
| 37 |
public _(RefCount<TSource> parent, IObserver<TSource> observer, IDisposable cancel) |
| 38 |
: base(observer, cancel) |
| 39 |
{ |
| 40 |
_parent = parent; |
| 41 |
} |
| 42 |
|
| 43 |
public IDisposable Run() |
| 44 |
{ |
| 45 |
var subscription = _parent._source.SubscribeSafe(this); |
| 46 |
|
| 47 |
lock (_parent._gate) |
| 48 |
{ |
| 49 |
if (++_parent._count == 1) |
| 50 |
{ |
| 51 |
_parent._connectableSubscription = _parent._source.Connect(); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
return Disposable.Create(() => |
| 56 |
{ |
| 57 |
subscription.Dispose(); |
| 58 |
|
| 59 |
lock (_parent._gate) |
| 60 |
{ |
| 61 |
if (--_parent._count == 0) |
| 62 |
{ |
| 63 |
_parent._connectableSubscription.Dispose(); |
| 64 |
} |
| 65 |
} |
| 66 |
}); |
| 67 |
} |
| 68 |
|
| 69 |
public void OnNext(TSource value) |
| 70 |
{ |
| 71 |
base._observer.OnNext(value); |
| 72 |
} |
| 73 |
|
| 74 |
public void OnError(Exception error) |
| 75 |
{ |
| 76 |
base._observer.OnError(error); |
| 77 |
base.Dispose(); |
| 78 |
} |
| 79 |
|
| 80 |
public void OnCompleted() |
| 81 |
{ |
| 82 |
base._observer.OnCompleted(); |
| 83 |
base.Dispose(); |
| 84 |
} |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
#endif |