Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/EventSource.cs

raw
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
5 namespace System.Reactive
6 {
7 class EventSource<T> : IEventSource<T>
8 {
9 private readonly IObservable<T> _source;
10 private readonly Dictionary<Delegate, Stack<IDisposable>> _subscriptions;
11 private readonly Action<Action<T>, /*object,*/ T> _invokeHandler;
12
13 public EventSource(IObservable<T> source, Action<Action<T>, /*object,*/ T> invokeHandler)
14 {
15 _source = source;
16 _invokeHandler = invokeHandler;
17 _subscriptions = new Dictionary<Delegate, Stack<IDisposable>>();
18 }
19
20 public event Action<T> OnNext
21 {
22 add
23 {
24 var gate = new object();
25 var isAdded = false;
26 var isDone = false;
27
28 var remove = new Action(() =>
29 {
30 lock (gate)
31 {
32 if (isAdded)
33 Remove(value);
34 else
35 isDone = true;
36 }
37 });
38
39 //
40 // [OK] Use of unsafe Subscribe: non-pretentious wrapper of an observable in an event; exceptions can occur during +=.
41 //
42 var d = _source.Subscribe/*Unsafe*/(
43 x => _invokeHandler(value, /*this,*/ x),
44 ex => { remove(); ex.Throw(); },
45 () => remove()
46 );
47
48 lock (gate)
49 {
50 if (!isDone)
51 {
52 Add(value, d);
53 isAdded = true;
54 }
55 }
56 }
57
58 remove
59 {
60 Remove(value);
61 }
62 }
63
64 private void Add(Delegate handler, IDisposable disposable)
65 {
66 lock (_subscriptions)
67 {
68 var l = new Stack<IDisposable>();
69 if (!_subscriptions.TryGetValue(handler, out l))
70 _subscriptions[handler] = l = new Stack<IDisposable>();
71
72 l.Push(disposable);
73 }
74 }
75
76 private void Remove(Delegate handler)
77 {
78 var d = default(IDisposable);
79
80 lock (_subscriptions)
81 {
82 var l = new Stack<IDisposable>();
83 if (_subscriptions.TryGetValue(handler, out l))
84 {
85 d = l.Pop();
86 if (l.Count == 0)
87 _subscriptions.Remove(handler);
88 }
89 }
90
91 if (d != null)
92 d.Dispose();
93 }
94 }
95 }