-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWrapperViewModel.cs
More file actions
45 lines (40 loc) · 1.47 KB
/
Copy pathWrapperViewModel.cs
File metadata and controls
45 lines (40 loc) · 1.47 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventHandlerLeakDemo
{
public class WrapperViewModel : IDisposable
{
private readonly WeakEventSubscription<Service, string> _serviceSubscription;
private bool _disposed;
public Service Service { get; }
public string? LastValue { get; private set; }
public WrapperViewModel(Service service)
{
Service = service ?? throw new ArgumentNullException(nameof(service));
_serviceSubscription = new WeakEventSubscription<Service, string>(
source: service,
attach: (s, h) => s.DataChanged += h,
detach: (s, h) => s.DataChanged -= h,
target: this,
// Has to be static to safeguard creating strong references with captured variables in this class
invoke: static (target, sender, args) =>
{
((WrapperViewModel)target).OnDataChanged(sender, args);
});
}
private void OnDataChanged(object? sender, string payload)
{
LastValue = payload;
Console.WriteLine($"WrapperViewModel received '{payload}' from {((Service)sender!).Name}");
}
public void Dispose()
{
if (_disposed) return;
_serviceSubscription.Dispose();
_disposed = true;
}
}
}