Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/MostRecent.cs

raw
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.Collections.Generic;
6 using System.Threading;
7
8 namespace System.Reactive.Linq.ObservableImpl
9 {
10 class MostRecent<TSource> : PushToPullAdapter<TSource, TSource>
11 {
12 private readonly TSource _initialValue;
13
14 public MostRecent(IObservable<TSource> source, TSource initialValue)
15 : base(source)
16 {
17 _initialValue = initialValue;
18 }
19
20 protected override PushToPullSink<TSource, TSource> Run(IDisposable subscription)
21 {
22 return new _(_initialValue, subscription);
23 }
24
25 class _ : PushToPullSink<TSource, TSource>
26 {
27 public _(TSource initialValue, IDisposable subscription)
28 : base(subscription)
29 {
30 _kind = NotificationKind.OnNext;
31 _value = initialValue;
32 }
33
34 private volatile NotificationKind _kind;
35 private TSource _value;
36 private Exception _error;
37
38 public override void OnNext(TSource value)
39 {
40 _value = value;
41 _kind = NotificationKind.OnNext; // Write last!
42 }
43
44 public override void OnError(Exception error)
45 {
46 base.Dispose();
47
48 _error = error;
49 _kind = NotificationKind.OnError; // Write last!
50 }
51
52 public override void OnCompleted()
53 {
54 base.Dispose();
55
56 _kind = NotificationKind.OnCompleted; // Write last!
57 }
58
59 public override bool TryMoveNext(out TSource current)
60 {
61 //
62 // Notice the _kind field is marked volatile and read before the other fields.
63 //
64 // In case of a concurrent change, we may read a stale OnNext value, which is
65 // fine because this push-to-pull adapter is about sampling.
66 //
67 switch (_kind)
68 {
69 case NotificationKind.OnNext:
70 current = _value;
71 return true;
72 case NotificationKind.OnError:
73 _error.Throw();
74 break;
75 case NotificationKind.OnCompleted:
76 break;
77 }
78
79 current = default(TSource);
80 return false;
81 }
82 }
83 }
84 }
85 #endif