forked from NullTale/UnityEventBus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscriberWrapper.cs
More file actions
99 lines (88 loc) · 3.16 KB
/
SubscriberWrapper.cs
File metadata and controls
99 lines (88 loc) · 3.16 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
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace UnityEventBus
{
/// <summary>
/// Subscriber container, helper class
/// </summary>
public sealed class SubscriberWrapper : IDisposable, ISubscriberWrapper
{
internal static Stack<SubscriberWrapper> s_WrappersPool = new Stack<SubscriberWrapper>(512);
private ISubscriberName m_Name;
private ISubscriberPriority m_Priority;
internal bool IsActive;
public Type Key;
public ISubscriber Subscriber;
public string Name => m_Name.Name;
public ISubscriber Target => Subscriber;
public int Order => m_Priority.Priority;
public int Index { get; set; }
// =======================================================================
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Invoke<TEvent, TInvoker>(in TEvent e, in TInvoker invoker) where TInvoker : IEventInvoker
{
#if DEBUG
invoker.Invoke(in e, in Subscriber);
#else
try
{
invoker.Invoke(in e, in Subscriber);
}
catch (Exception exception)
{
UnityEngine.Debug.LogError($"{this}; Exception: {exception}");
}
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SubscriberWrapper(ISubscriber listener, Type type)
{
Setup(listener, type);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Setup(ISubscriber listener, Type type)
{
IsActive = true;
Subscriber = listener;
m_Name = listener as ISubscriberName ?? Extensions.s_DefaultSubscriberName;
m_Priority = listener as ISubscriberPriority ?? Extensions.s_DefaultSubscriberPriority;
Key = type;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
return Subscriber == ((SubscriberWrapper)obj).Subscriber;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return Subscriber.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
IsActive = false;
Subscriber = null;
m_Name = null;
m_Priority = null;
s_WrappersPool.Push(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static SubscriberWrapper Create(ISubscriber listener, Type key)
{
if (s_WrappersPool.Count > 0)
{
var wrapper = s_WrappersPool.Pop();
wrapper.Setup(listener, key);
return wrapper;
}
else
return new SubscriberWrapper(listener, key);
}
public override string ToString()
{
return $"Sub: <Name> {Name}, <Type> {Subscriber.GetType()}, <Key> {Key}";
}
}
}