-
Notifications
You must be signed in to change notification settings - Fork 792
Expand file tree
/
Copy pathAsyncJoinObserver.cs
More file actions
96 lines (77 loc) · 3.05 KB
/
Copy pathAsyncJoinObserver.cs
File metadata and controls
96 lines (77 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Threading;
using System.Threading.Tasks;
namespace System.Reactive.Joins
{
internal sealed class AsyncJoinObserver<T> : AsyncObserverBase<Notification<T>>, IAsyncJoinObserver
{
private readonly IAsyncObservable<T> _source;
private readonly Func<Exception, ValueTask> _onError;
private readonly List<ActiveAsyncPlan> _activePlans = new();
private readonly SingleAssignmentAsyncDisposable _subscription = new();
private IAsyncGate _gate;
private bool _isDisposed;
public AsyncJoinObserver(IAsyncObservable<T> source, Func<Exception, ValueTask> onError)
{
_source = source;
_onError = onError;
}
public Queue<Notification<T>> Queue { get; } = new Queue<Notification<T>>();
public void Dequeue() => Queue.Dequeue();
public void AddActivePlan(ActiveAsyncPlan activePlan)
{
_activePlans.Add(activePlan);
}
internal async Task RemoveActivePlan(ActiveAsyncPlan activePlan)
{
_activePlans.Remove(activePlan);
if (_activePlans.Count == 0)
{
await DisposeAsync().ConfigureAwait(false);
}
}
public async ValueTask DisposeAsync()
{
if (!_isDisposed)
{
await _subscription.DisposeAsync().ConfigureAwait(false);
_isDisposed = true;
}
}
public async Task SubscribeAsync(IAsyncGate gate)
{
_gate = gate;
var d = await _source.Materialize().SubscribeSafeAsync(this).ConfigureAwait(false);
await _subscription.AssignAsync(d).ConfigureAwait(false);
}
protected override ValueTask OnCompletedAsyncCore() => default;
protected override ValueTask OnErrorAsyncCore(Exception error) => default;
protected override async ValueTask OnNextAsyncCore(Notification<T> notification)
{
using (await _gate.LockAsync().ConfigureAwait(false))
{
if (!_isDisposed)
{
if (notification.Kind == NotificationKind.OnError)
{
await _onError(notification.Exception).ConfigureAwait(false);
}
else
{
Queue.Enqueue(notification);
var plans = _activePlans.ToArray();
for (var i = 0; i < plans.Length; i++)
{
await plans[i].Match().ConfigureAwait(false); // REVIEW: Consider concurrent matching.
}
}
}
}
}
}
}