Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/QueryLanguage.Awaiter.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 HAS_AWAIT
4 using System;
5 using System.Threading;
6 using System.Reactive.Disposables;
7 using System.Reactive.Subjects;
8
9 namespace System.Reactive.Linq
10 {
11 internal partial class QueryLanguage
12 {
13 public virtual AsyncSubject<TSource> GetAwaiter<TSource>(IObservable<TSource> source)
14 {
15 return RunAsync<TSource>(source, CancellationToken.None);
16 }
17
18 public virtual AsyncSubject<TSource> GetAwaiter<TSource>(IConnectableObservable<TSource> source)
19 {
20 return RunAsync<TSource>(source, CancellationToken.None);
21 }
22
23 public virtual AsyncSubject<TSource> RunAsync<TSource>(IObservable<TSource> source, CancellationToken cancellationToken)
24 {
25 var s = new AsyncSubject<TSource>();
26
27 if (cancellationToken.IsCancellationRequested)
28 {
29 return Cancel(s);
30 }
31
32 var d = source.SubscribeSafe(s);
33
34 if (cancellationToken.CanBeCanceled)
35 {
36 RegisterCancelation(s, d, cancellationToken);
37 }
38
39 return s;
40 }
41
42 public virtual AsyncSubject<TSource> RunAsync<TSource>(IConnectableObservable<TSource> source, CancellationToken cancellationToken)
43 {
44 var s = new AsyncSubject<TSource>();
45
46 if (cancellationToken.IsCancellationRequested)
47 {
48 return Cancel(s);
49 }
50
51 var d = source.SubscribeSafe(s);
52 var c = source.Connect();
53
54 if (cancellationToken.CanBeCanceled)
55 {
56 RegisterCancelation(s, new CompositeDisposable(d, c), cancellationToken);
57 }
58
59 return s;
60 }
61
62 private static AsyncSubject<T> Cancel<T>(AsyncSubject<T> subject)
63 {
64 subject.OnError(new OperationCanceledException());
65 return subject;
66 }
67
68 private static void RegisterCancelation<T>(AsyncSubject<T> subject, IDisposable subscription, CancellationToken token)
69 {
70 //
71 // Separate method used to avoid heap allocation of closure when no cancellation is needed,
72 // e.g. when CancellationToken.None is provided to the RunAsync overloads.
73 //
74
75 var ctr = token.Register(() =>
76 {
77 subscription.Dispose();
78 Cancel(subject);
79 });
80
81 //
82 // No null-check for ctr is needed:
83 //
84 // - CancellationTokenRegistration is a struct
85 // - Registration will succeed 99% of the time, no warranting an attempt to avoid spurious Subscribe calls
86 //
87 subject.Subscribe(Stubs<T>.Ignore, _ => ctr.Dispose(), ctr.Dispose);
88 }
89 }
90 }
91 #endif