| 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.Threading; |
| 5 |
|
| 6 |
namespace System.Reactive |
| 7 |
{ |
| 8 |
/// <summary> |
| 9 |
/// Base class for implementation of query operators, providing a lightweight sink that can be disposed to mute the outgoing observer. |
| 10 |
/// </summary> |
| 11 |
/// <typeparam name="TSource">Type of the resulting sequence's elements.</typeparam> |
| 12 |
/// <remarks>Implementations of sinks are responsible to enforce the message grammar on the associated observer. Upon sending a terminal message, a pairing Dispose call should be made to trigger cancellation of related resources and to mute the outgoing observer.</remarks> |
| 13 |
internal abstract class Sink<TSource> : IDisposable |
| 14 |
{ |
| 15 |
protected internal volatile IObserver<TSource> _observer; |
| 16 |
private IDisposable _cancel; |
| 17 |
|
| 18 |
public Sink(IObserver<TSource> observer, IDisposable cancel) |
| 19 |
{ |
| 20 |
_observer = observer; |
| 21 |
_cancel = cancel; |
| 22 |
} |
| 23 |
|
| 24 |
public virtual void Dispose() |
| 25 |
{ |
| 26 |
_observer = NopObserver<TSource>.Instance; |
| 27 |
|
| 28 |
var cancel = Interlocked.Exchange(ref _cancel, null); |
| 29 |
if (cancel != null) |
| 30 |
{ |
| 31 |
cancel.Dispose(); |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
public IObserver<TSource> GetForwarder() |
| 36 |
{ |
| 37 |
return new _(this); |
| 38 |
} |
| 39 |
|
| 40 |
class _ : IObserver<TSource> |
| 41 |
{ |
| 42 |
private readonly Sink<TSource> _forward; |
| 43 |
|
| 44 |
public _(Sink<TSource> forward) |
| 45 |
{ |
| 46 |
_forward = forward; |
| 47 |
} |
| 48 |
|
| 49 |
public void OnNext(TSource value) |
| 50 |
{ |
| 51 |
_forward._observer.OnNext(value); |
| 52 |
} |
| 53 |
|
| 54 |
public void OnError(Exception error) |
| 55 |
{ |
| 56 |
_forward._observer.OnError(error); |
| 57 |
_forward.Dispose(); |
| 58 |
} |
| 59 |
|
| 60 |
public void OnCompleted() |
| 61 |
{ |
| 62 |
_forward._observer.OnCompleted(); |
| 63 |
_forward.Dispose(); |
| 64 |
} |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
#endif |