Repository navigation
Expand file tree
/
Copy pathRefCount.cs
More file actions
56 lines (45 loc) · 1.79 KB
/
Copy pathRefCount.cs
File metadata and controls
56 lines (45 loc) · 1.79 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
// Copyright (c) 2011-2023 Roland Pheasant. All rights reserved.
// Roland Pheasant licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace DynamicData.Cache.Internal;
internal sealed class RefCount<TObject, TKey>(IObservable<IChangeSet<TObject, TKey>> source)
where TObject : notnull
where TKey : notnull
{
private readonly object _locker = new();
private readonly IObservable<IChangeSet<TObject, TKey>> _source = source ?? throw new ArgumentNullException(nameof(source));
private IObservableCache<TObject, TKey>? _cache;
private int _refCount;
public IObservable<IChangeSet<TObject, TKey>> Run() => Observable.Create<IChangeSet<TObject, TKey>>(
observer =>
{
lock (_locker)
{
if (++_refCount == 1)
{
_cache = _source.AsObservableCache();
}
}
if (_cache is null)
{
throw new InvalidOperationException(nameof(_cache) + " is null");
}
var subscriber = _cache.Connect().SubscribeSafe(observer);
return Disposable.Create(() =>
{
subscriber.Dispose();
IDisposable? cacheToDispose = null;
lock (_locker)
{
if (--_refCount == 0)
{
cacheToDispose = _cache;
_cache = null;
}
}
cacheToDispose?.Dispose();
});
});
}