-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathEventBus.Core.pas
362 lines (318 loc) · 11 KB
/
EventBus.Core.pas
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
{ *******************************************************************************
Copyright 2016-2019 Daniele Spinetti
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************** }
unit EventBus.Core;
interface
uses
System.SyncObjs, EventBus.Subscribers, Generics.Collections,
System.SysUtils, System.Classes, Router4D.Props;
type
TEventBus = class(TInterfacedObject, IEventBus)
var
FTypesOfGivenSubscriber: TObjectDictionary<TObject, TList<TClass>>;
FSubscriptionsOfGivenEventType
: TObjectDictionary<TClass, TObjectList<TSubscription>>;
FCustomClonerDict: TDictionary<String, TCloneEventMethod>;
FOnCloneEvent: TCloneEventCallback;
procedure Subscribe(ASubscriber: TObject;
ASubscriberMethod: TSubscriberMethod);
procedure UnsubscribeByEventType(ASubscriber: TObject; AEventType: TClass);
procedure InvokeSubscriber(ASubscription: TSubscription; AEvent: TObject);
function GenerateTProc(ASubscription: TSubscription;
AEvent: TObject): TProc;
function GenerateThreadProc(ASubscription: TSubscription; AEvent: TObject)
: TThreadProcedure;
protected
procedure SetOnCloneEvent(const aCloneEvent: TCloneEventCallback);
function CloneEvent(AEvent: TObject): TObject; virtual;
procedure PostToSubscription(ASubscription: TSubscription; AEvent: TObject;
AIsMainThread: Boolean); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure RegisterSubscriber(ASubscriber: TObject); virtual;
function IsRegistered(ASubscriber: TObject): Boolean;
procedure Unregister(ASubscriber: TObject); virtual;
procedure Post(AEvent: TObject; const AContext: String = '';
AEventOwner: Boolean = true); virtual;
property TypesOfGivenSubscriber: TObjectDictionary < TObject,
TList < TClass >> read FTypesOfGivenSubscriber;
property SubscriptionsOfGivenEventType: TObjectDictionary < TClass,
TObjectList < TSubscription >> read FSubscriptionsOfGivenEventType;
property OnCloneEvent: TCloneEventCallback write SetOnCloneEvent;
procedure AddCustomClassCloning(const AQualifiedClassName: String;
const aCloneEvent: TCloneEventMethod);
procedure RemoveCustomClassCloning(const AQualifiedClassName: String);
end;
implementation
uses
System.Rtti,
{$IF CompilerVersion >= 28.0}
System.Threading,
{$ENDIF}
RTTIUtilsU;
var
FMREWSync: TMultiReadExclusiveWriteSynchronizer;
{ TEventBus }
constructor TEventBus.Create;
begin
inherited Create;
FSubscriptionsOfGivenEventType := TObjectDictionary < TClass,
TObjectList < TSubscription >>.Create([doOwnsValues]);
FTypesOfGivenSubscriber := TObjectDictionary < TObject,
TList < TClass >>.Create([doOwnsValues]);
FCustomClonerDict := TDictionary<String, TCloneEventMethod>.Create;
end;
destructor TEventBus.Destroy;
begin
FreeAndNil(FSubscriptionsOfGivenEventType);
FreeAndNil(FTypesOfGivenSubscriber);
FreeAndNil(FCustomClonerDict);
inherited;
end;
procedure TEventBus.AddCustomClassCloning(const AQualifiedClassName: String;
const aCloneEvent: TCloneEventMethod);
begin
FCustomClonerDict.Add(AQualifiedClassName, aCloneEvent);
end;
function TEventBus.CloneEvent(AEvent: TObject): TObject;
var
LCloneEvent: TCloneEventMethod;
begin
if FCustomClonerDict.TryGetValue(AEvent.QualifiedClassName, LCloneEvent) then
Result := LCloneEvent(AEvent)
else if Assigned(FOnCloneEvent) then
Result := FOnCloneEvent(AEvent)
else
Result := TRTTIUtils.Clone(AEvent);
end;
function TEventBus.GenerateThreadProc(ASubscription: TSubscription;
AEvent: TObject): TThreadProcedure;
begin
Result := procedure
begin
if ASubscription.Active then
begin
ASubscription.SubscriberMethod.Method.Invoke(ASubscription.Subscriber,
[AEvent]);
end;
end;
end;
function TEventBus.GenerateTProc(ASubscription: TSubscription;
AEvent: TObject): TProc;
begin
Result := procedure
begin
if ASubscription.Active then
begin
ASubscription.SubscriberMethod.Method.Invoke(ASubscription.Subscriber,
[AEvent]);
end;
end;
end;
procedure TEventBus.InvokeSubscriber(ASubscription: TSubscription;
AEvent: TObject);
begin
try
ASubscription.SubscriberMethod.Method.Invoke(ASubscription.Subscriber,
[AEvent]);
except
on E: Exception do
begin
raise Exception.CreateFmt
('Error invoking subscriber method. Subscriber class: %s. Event type: %s. Original exception: %s: %s',
[ASubscription.Subscriber.ClassName,
ASubscription.SubscriberMethod.EventType.ClassName, E.ClassName,
E.Message]);
end;
end;
end;
function TEventBus.IsRegistered(ASubscriber: TObject): Boolean;
begin
FMREWSync.BeginRead;
try
Result := FTypesOfGivenSubscriber.ContainsKey(ASubscriber);
finally
FMREWSync.EndRead;
end;
end;
procedure TEventBus.Post(AEvent: TObject; const AContext: String = '';
AEventOwner: Boolean = true);
var
LSubscriptions: TObjectList<TSubscription>;
LSubscription: TSubscription;
LEvent: TObject;
LIsMainThread: Boolean;
begin
FMREWSync.BeginRead;
try
try
LIsMainThread := MainThreadID = TThread.CurrentThread.ThreadID;
FSubscriptionsOfGivenEventType.TryGetValue(AEvent.ClassType,
LSubscriptions);
if (not Assigned(LSubscriptions)) then
Exit;
for LSubscription in LSubscriptions do
begin
if not LSubscription.Active then
continue;
if ((not AContext.IsEmpty) and (LSubscription.Context <> AContext)) then
continue;
LEvent := CloneEvent(AEvent);
PostToSubscription(LSubscription, LEvent, LIsMainThread);
end;
finally
if (AEventOwner and Assigned(AEvent)) then
AEvent.Free;
end;
finally
FMREWSync.EndRead;
end;
end;
procedure TEventBus.PostToSubscription(ASubscription: TSubscription;
AEvent: TObject; AIsMainThread: Boolean);
begin
if not Assigned(ASubscription.Subscriber) then
Exit;
case ASubscription.SubscriberMethod.ThreadMode of
Posting:
InvokeSubscriber(ASubscription, AEvent);
Main:
if (AIsMainThread) then
InvokeSubscriber(ASubscription, AEvent)
else
TThread.Queue(nil, GenerateThreadProc(ASubscription, AEvent));
Background:
if (AIsMainThread) then
{$IF CompilerVersion >= 28.0}
TTask.Run(GenerateTProc(ASubscription, AEvent))
{$ELSE}
TThread.CreateAnonymousThread(GenerateTProc(ASubscription,
AEvent)).Start
{$ENDIF}
else
InvokeSubscriber(ASubscription, AEvent);
Async:
{$IF CompilerVersion >= 28.0}
TTask.Run(GenerateTProc(ASubscription, AEvent));
{$ELSE}
TThread.CreateAnonymousThread(GenerateTProc(ASubscription, AEvent)).Start;
{$ENDIF}
else
raise Exception.Create('Unknown thread mode');
end;
end;
procedure TEventBus.RegisterSubscriber(ASubscriber: TObject);
var
LSubscriberClass: TClass;
LSubscriberMethods: TArray<TSubscriberMethod>;
LSubscriberMethod: TSubscriberMethod;
begin
FMREWSync.BeginWrite;
try
LSubscriberClass := ASubscriber.ClassType;
LSubscriberMethods := TSubscribersFinder.FindSubscriberMethods
(LSubscriberClass, true);
for LSubscriberMethod in LSubscriberMethods do
Subscribe(ASubscriber, LSubscriberMethod);
finally
FMREWSync.EndWrite;
end;
end;
procedure TEventBus.RemoveCustomClassCloning(const AQualifiedClassName: String);
begin
// No exception is thrown if the key is not in the dictionary
FCustomClonerDict.Remove(AQualifiedClassName);
end;
procedure TEventBus.SetOnCloneEvent(const aCloneEvent: TCloneEventCallback);
begin
FOnCloneEvent := aCloneEvent;
end;
procedure TEventBus.Subscribe(ASubscriber: TObject;
ASubscriberMethod: TSubscriberMethod);
var
LEventType: TClass;
LNewSubscription: TSubscription;
LSubscriptions: TObjectList<TSubscription>;
LSubscribedEvents: TList<TClass>;
begin
LEventType := ASubscriberMethod.EventType;
LNewSubscription := TSubscription.Create(ASubscriber, ASubscriberMethod);
if (not FSubscriptionsOfGivenEventType.ContainsKey(LEventType)) then
begin
LSubscriptions := TObjectList<TSubscription>.Create();
FSubscriptionsOfGivenEventType.Add(LEventType, LSubscriptions);
end
else
begin
LSubscriptions := FSubscriptionsOfGivenEventType.Items[LEventType];
if (LSubscriptions.Contains(LNewSubscription)) then
raise Exception.CreateFmt('Subscriber %s already registered to event %s ',
[ASubscriber.ClassName, LEventType.ClassName]);
end;
LSubscriptions.Add(LNewSubscription);
if (not FTypesOfGivenSubscriber.TryGetValue(ASubscriber, LSubscribedEvents))
then
begin
LSubscribedEvents := TList<TClass>.Create;
FTypesOfGivenSubscriber.Add(ASubscriber, LSubscribedEvents);
end;
LSubscribedEvents.Add(LEventType);
end;
procedure TEventBus.Unregister(ASubscriber: TObject);
var
LSubscribedTypes: TList<TClass>;
LEventType: TClass;
begin
FMREWSync.BeginWrite;
try
if FTypesOfGivenSubscriber.TryGetValue(ASubscriber, LSubscribedTypes) then
begin
for LEventType in LSubscribedTypes do
UnsubscribeByEventType(ASubscriber, LEventType);
FTypesOfGivenSubscriber.Remove(ASubscriber);
end;
// else {
// Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
// }
finally
FMREWSync.EndWrite;
end;
end;
procedure TEventBus.UnsubscribeByEventType(ASubscriber: TObject;
AEventType: TClass);
var
LSubscriptions: TObjectList<TSubscription>;
LSize, I: Integer;
LSubscription: TSubscription;
begin
LSubscriptions := FSubscriptionsOfGivenEventType.Items[AEventType];
if (not Assigned(LSubscriptions)) or (LSubscriptions.Count < 1) then
Exit;
LSize := LSubscriptions.Count;
for I := LSize - 1 downto 0 do
begin
LSubscription := LSubscriptions[I];
// Notes: In case the subscriber has been freed but it didn't unregister itself, calling
// LSubscription.Subscriber.Equals() will cause Access Violation, so we use '=' instead.
if LSubscription.Subscriber = ASubscriber then
begin
LSubscription.Active := false;
LSubscriptions.Delete(I);
end;
end;
end;
initialization
FMREWSync := TMultiReadExclusiveWriteSynchronizer.Create;
finalization
FMREWSync.Free;
end.