| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
using System.Collections.Generic; |
| 4 |
using System.Reactive.Disposables; |
| 5 |
using System.Reactive.Linq; |
| 6 |
|
| 7 |
namespace System.Reactive.Joins |
| 8 |
{ |
| 9 |
internal interface IJoinObserver : IDisposable |
| 10 |
{ |
| 11 |
void Subscribe(object gate); |
| 12 |
void Dequeue(); |
| 13 |
} |
| 14 |
|
| 15 |
internal sealed class JoinObserver<T> : ObserverBase<Notification<T>>, IJoinObserver |
| 16 |
{ |
| 17 |
private object gate; |
| 18 |
private readonly IObservable<T> source; |
| 19 |
private readonly Action<Exception> onError; |
| 20 |
private List<ActivePlan> activePlans; |
| 21 |
public Queue<Notification<T>> Queue { get; private set; } |
| 22 |
private readonly SingleAssignmentDisposable subscription; |
| 23 |
private bool isDisposed; |
| 24 |
|
| 25 |
public JoinObserver(IObservable<T> source, Action<Exception> onError) |
| 26 |
{ |
| 27 |
this.source = source; |
| 28 |
this.onError = onError; |
| 29 |
Queue = new Queue<Notification<T>>(); |
| 30 |
subscription = new SingleAssignmentDisposable(); |
| 31 |
activePlans = new List<ActivePlan>(); |
| 32 |
} |
| 33 |
|
| 34 |
public void AddActivePlan(ActivePlan activePlan) |
| 35 |
{ |
| 36 |
activePlans.Add(activePlan); |
| 37 |
} |
| 38 |
|
| 39 |
public void Subscribe(object gate) |
| 40 |
{ |
| 41 |
this.gate = gate; |
| 42 |
subscription.Disposable = source.Materialize().SubscribeSafe(this); |
| 43 |
} |
| 44 |
|
| 45 |
public void Dequeue() |
| 46 |
{ |
| 47 |
Queue.Dequeue(); |
| 48 |
} |
| 49 |
|
| 50 |
protected override void OnNextCore(Notification<T> notification) |
| 51 |
{ |
| 52 |
lock (gate) |
| 53 |
{ |
| 54 |
if (!isDisposed) |
| 55 |
{ |
| 56 |
if (notification.Kind == NotificationKind.OnError) |
| 57 |
{ |
| 58 |
onError(notification.Exception); |
| 59 |
return; |
| 60 |
} |
| 61 |
|
| 62 |
Queue.Enqueue(notification); |
| 63 |
foreach (var activePlan in activePlans.ToArray()) |
| 64 |
activePlan.Match(); |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
protected override void OnErrorCore(Exception exception) |
| 70 |
{ |
| 71 |
} |
| 72 |
|
| 73 |
protected override void OnCompletedCore() |
| 74 |
{ |
| 75 |
} |
| 76 |
|
| 77 |
internal void RemoveActivePlan(ActivePlan activePlan) |
| 78 |
{ |
| 79 |
activePlans.Remove(activePlan); |
| 80 |
if (activePlans.Count == 0) |
| 81 |
Dispose(); |
| 82 |
} |
| 83 |
|
| 84 |
protected override void Dispose(bool disposing) |
| 85 |
{ |
| 86 |
base.Dispose(disposing); |
| 87 |
|
| 88 |
if (!isDisposed) |
| 89 |
{ |
| 90 |
if (disposing) |
| 91 |
subscription.Dispose(); |
| 92 |
|
| 93 |
isDisposed = true; |
| 94 |
} |
| 95 |
} |
| 96 |
} |
| 97 |
} |