Repository navigation
Expand file tree
/
Copy pathRefCount.cs
More file actions
53 lines (44 loc) · 1.66 KB
/
Copy pathRefCount.cs
File metadata and controls
53 lines (44 loc) · 1.66 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
// 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.List.Internal;
internal sealed class RefCount<T>(IObservable<IChangeSet<T>> source)
where T : notnull
{
private readonly object _locker = new();
private IObservableList<T>? _list;
private int _refCount;
public IObservable<IChangeSet<T>> Run() => Observable.Create<IChangeSet<T>>(
observer =>
{
lock (_locker)
{
if (++_refCount == 1)
{
_list = source.AsObservableList();
}
}
if (_list is null)
{
throw new InvalidOperationException("The list is null despite having reference counting.");
}
var subscriber = _list.Connect().SubscribeSafe(observer);
return Disposable.Create(
() =>
{
subscriber.Dispose();
IDisposable? listToDispose = null;
lock (_locker)
{
if (--_refCount == 0)
{
listToDispose = _list;
_list = null;
}
}
listToDispose?.Dispose();
});
});
}