-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathObserver.cs
More file actions
103 lines (95 loc) · 2.9 KB
/
Copy pathObserver.cs
File metadata and controls
103 lines (95 loc) · 2.9 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
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using UnityEngine;
namespace DATA.Scripts.Core
{
public class Observer : Singleton<Observer>
{
private readonly Dictionary<string, List<Action>> _listeners = new Dictionary<string, List<Action>>();
private readonly Dictionary<string, List<Action<object>>> _listenersWithParam = new Dictionary<string, List<Action<object>>>();
public void RegisterObserver(string key, Action action)
{
List<Action> actions;
if (_listeners.TryGetValue(key, out var listener))
{
actions = listener;
}
else
{
actions = new List<Action>();
_listeners.Add(key, actions);
}
actions.Add(action);
}
public void RegisterObserver(string key, Action<object> action)
{
List<Action<object>> actions;
if (_listenersWithParam.TryGetValue(key, out var listener))
{
actions = listener;
}
else
{
actions = new List<Action<object>>();
_listenersWithParam.Add(key, actions);
}
actions.Add(action);
}
public void NotifyObservers(string key, object param)
{
if (_listenersWithParam.TryGetValue(key, out var listener))
{
foreach (Action<object> a in listener)
{
try
{
a?.Invoke(param);
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
else
{
Debug.LogErrorFormat("listener {0} not exist", key);
}
}
public void NotifyObservers(string key)
{
if (_listeners.TryGetValue(key, value: out var listener))
{
foreach (Action a in listener)
{
try
{
a?.Invoke();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
else
{
Debug.LogErrorFormat("listener {0} not exist", key);
}
}
public void RemoveObserver(string key, Action<object> action)
{
if (_listenersWithParam.TryGetValue(key, out var listener))
{
listener.Remove(action);
}
}
public void RemoveObserver(string key, Action action)
{
if (_listeners.TryGetValue(key, out var listener))
{
listener.Remove(action);
}
}
}
}