Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Core/Reactive/Internal/AutoDetachObserver.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.Reactive.Disposables;
4
5 namespace System.Reactive
6 {
7 class AutoDetachObserver<T> : ObserverBase<T>
8 {
9 private readonly IObserver<T> observer;
10 private readonly SingleAssignmentDisposable m = new SingleAssignmentDisposable();
11
12 public AutoDetachObserver(IObserver<T> observer)
13 {
14 this.observer = observer;
15 }
16
17 public IDisposable Disposable
18 {
19 set { m.Disposable = value; }
20 }
21
22 protected override void OnNextCore(T value)
23 {
24 //
25 // Safeguarding of the pipeline against rogue observers is required for proper
26 // resource cleanup. Consider the following example:
27 //
28 // var xs = Observable.Interval(TimeSpan.FromSeconds(1));
29 // var ys = <some random sequence>;
30 // var res = xs.CombineLatest(ys, (x, y) => x + y);
31 //
32 // The marble diagram of the query above looks as follows:
33 //
34 // xs -----0-----1-----2-----3-----4-----5-----6-----7-----8-----9---...
35 // | | | | | | | | |
36 // ys --------4--+--5--+-----+--2--+--1--+-----+-----+--0--+-----+---...
37 // | | | | | | | | | | | | | |
38 // v v v v v v v v v v v v v v
39 // res --------4--5--6--7-----8--5--6--5--6-----7-----8--7--8-----9---...
40 // |
41 // @#&
42 //
43 // Notice the free-threaded nature of Rx, where messages on the resulting sequence
44 // are produced by either of the two input sequences to CombineLatest.
45 //
46 // Now assume an exception happens in the OnNext callback for the observer of res,
47 // at the indicated point marked with @#& above. The callback runs in the context
48 // of ys, so the exception will take down the scheduler thread of ys. This by
49 // itself is a problem (that can be mitigated by a Catch operator on IScheduler),
50 // but notice how the timer that produces xs is kept alive.
51 //
52 // The safe-guarding code below ensures the acquired resources are disposed when
53 // the user callback throws.
54 //
55 var __noError = false;
56 try
57 {
58 observer.OnNext(value);
59 __noError = true;
60 }
61 finally
62 {
63 if (!__noError)
64 Dispose();
65 }
66 }
67
68 protected override void OnErrorCore(Exception exception)
69 {
70 try
71 {
72 observer.OnError(exception);
73 }
74 finally
75 {
76 Dispose();
77 }
78 }
79
80 protected override void OnCompletedCore()
81 {
82 try
83 {
84 observer.OnCompleted();
85 }
86 finally
87 {
88 Dispose();
89 }
90 }
91
92 protected override void Dispose(bool disposing)
93 {
94 base.Dispose(disposing);
95
96 if (disposing)
97 m.Dispose();
98 }
99 }
100 }