-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRefresher.cs
62 lines (49 loc) · 1.69 KB
/
Refresher.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
public interface IRefresher
{
void Subscribe(String ChannelName, Action Event);
void Unsubscribe(String ChannelName, Action Event);
void CallRequestRefresh(String ChannelName);
}
public class Refresher : IRefresher
{
private Dictionary<String, Action> Subscriptions { get; init; }
public Refresher()
{
Subscriptions = new Dictionary<String, Action>();
}
public void CallRequestRefresh(String ChannelName)
{
Subscriptions[ChannelName]?.Invoke();
}
public void Subscribe(String ChannelName, Action Event)
{
//Create a new delegate if there is nothing on this channel yet.
if (!Subscriptions.ContainsKey(ChannelName))
Subscriptions[ChannelName] = () => { };
//Prevent multiple subscribtions by the same page...
if (Subscriptions[ChannelName] == null ||
!Subscriptions[ChannelName].GetInvocationList().Select(il => il.Method).Contains(Event.Method))
{
Subscriptions[ChannelName] += Event;
}
Subscriptions[ChannelName] += Event;
}
public void Unsubscribe(String ChannelName, Action Event)
{
Console.WriteLine("Removing subscription for " + ChannelName.ToString());
//Preventing double un-subscription.
if (Subscriptions[ChannelName] != null)
{
Action eventMethod = (Action)Subscriptions[ChannelName]
.GetInvocationList()
.FirstOrDefault(il => il.Method == Event.Method);
if (eventMethod != null)
{
Subscriptions[ChannelName] -= eventMethod;
}
}
}
}