-
Notifications
You must be signed in to change notification settings - Fork 3
/
MessengerHub.cs
319 lines (278 loc) · 11.5 KB
/
MessengerHub.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Messenger.Subscriptions;
using Messenger.ThreadRunners;
namespace Messenger
{
public class MessengerHub : IMessenger
{
private readonly Dictionary<Type, Dictionary<Guid, BaseSubscription>> _subscriptions =
new Dictionary<Type, Dictionary<Guid, BaseSubscription>>();
public MessengerSubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, MessengerReference reference = MessengerReference.Weak, string tag = null)
where TMessage : MessengerMessage
{
return SubscribeInternal(deliveryAction, new SimpleActionRunner(), reference, tag);
}
public MessengerSubscriptionToken SubscribeOnMainThread<TMessage>(Action<TMessage> deliveryAction,
MessengerReference reference = MessengerReference.Weak, string tag = null)
where TMessage : MessengerMessage
{
return SubscribeInternal(deliveryAction, new MainThreadActionRunner(), reference, tag);
}
public MessengerSubscriptionToken SubscribeOnThreadPoolThread<TMessage>(Action<TMessage> deliveryAction, MessengerReference reference = MessengerReference.Weak, string tag = null)
where TMessage : MessengerMessage
{
return SubscribeInternal(deliveryAction, new ThreadPoolActionRunner(), reference, tag);
}
private MessengerSubscriptionToken SubscribeInternal<TMessage>(Action<TMessage> deliveryAction, IActionRunner actionRunner, MessengerReference reference, string tag)
where TMessage : MessengerMessage
{
if (deliveryAction == null)
{
throw new ArgumentNullException(nameof(deliveryAction));
}
BaseSubscription subscription;
switch (reference)
{
case MessengerReference.Strong:
subscription = new StrongSubscription<TMessage>(actionRunner, deliveryAction, tag);
break;
case MessengerReference.Weak:
subscription = new WeakSubscription<TMessage>(actionRunner, deliveryAction, tag);
break;
default:
throw new ArgumentOutOfRangeException(nameof(reference), "reference type unexpected " + reference);
}
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
messageSubscriptions = new Dictionary<Guid, BaseSubscription>();
_subscriptions[typeof(TMessage)] = messageSubscriptions;
}
//Console.WriteLine("Adding subscription {0} for {1}", subscription.Id, typeof(TMessage).Name);
messageSubscriptions[subscription.Id] = subscription;
PublishSubscriberChangeMessage<TMessage>(messageSubscriptions);
}
return new MessengerSubscriptionToken(
subscription.Id,
() => InternalUnsubscribe<TMessage>(subscription.Id),
deliveryAction);
}
public void Unsubscribe<TMessage>(MessengerSubscriptionToken mvxSubscriptionId) where TMessage : MessengerMessage
{
InternalUnsubscribe<TMessage>(mvxSubscriptionId.Id);
}
private void InternalUnsubscribe<TMessage>(Guid subscriptionGuid) where TMessage : MessengerMessage
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
if (messageSubscriptions.ContainsKey(subscriptionGuid))
{
//Console.WriteLine("Removing subscription {0}", subscriptionGuid);
messageSubscriptions.Remove(subscriptionGuid);
// Note - we could also remove messageSubscriptions if empty here
// - but this isn't needed in our typical apps
}
}
PublishSubscriberChangeMessage<TMessage>(messageSubscriptions);
}
}
protected virtual void PublishSubscriberChangeMessage<TMessage>(
Dictionary<Guid, BaseSubscription> messageSubscriptions)
where TMessage : MessengerMessage
{
PublishSubscriberChangeMessage(typeof(TMessage), messageSubscriptions);
}
protected virtual void PublishSubscriberChangeMessage(
Type messageType,
Dictionary<Guid, BaseSubscription> messageSubscriptions)
{
var newCount = messageSubscriptions?.Count ?? 0;
Publish(new MessengerSubscriberChangeMessage(this, messageType, newCount));
}
public bool HasSubscriptionsFor<TMessage>()
where TMessage : MessengerMessage
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
return false;
}
return messageSubscriptions.Any();
}
}
public int CountSubscriptionsFor<TMessage>() where TMessage : MessengerMessage
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
return 0;
}
return messageSubscriptions.Count;
}
}
public bool HasSubscriptionsForTag<TMessage>(string tag) where TMessage : MessengerMessage
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
return false;
}
return messageSubscriptions.Any(x => x.Value.Tag == tag);
}
}
public int CountSubscriptionsForTag<TMessage>(string tag) where TMessage : MessengerMessage
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
return 0;
}
return messageSubscriptions.Count(x => x.Value.Tag == tag);
}
}
public IList<string> GetSubscriptionTagsFor<TMessage>() where TMessage : MessengerMessage
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(typeof(TMessage), out messageSubscriptions))
{
return new List<string>(0);
}
return messageSubscriptions.Select(x => x.Value.Tag).ToList();
}
}
public void Publish<TMessage>(TMessage message) where TMessage : MessengerMessage
{
if (typeof(TMessage) == typeof(MessengerMessage))
{
//Console.WriteLine("MessengerMessage publishing not allowed - this normally suggests non-specific generic used in calling code - switching to message.GetType()");
Publish(message, message.GetType());
return;
}
Publish(message, typeof(TMessage));
}
public void Publish(MessengerMessage message)
{
Publish(message, message.GetType());
}
public void Publish(MessengerMessage message, Type messageType)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
List<BaseSubscription> toNotify = null;
lock (this)
{
/*
MvxTrace.Trace("Found {0} subscriptions of all types", _subscriptions.Count);
foreach (var t in _subscriptions.Keys)
{
MvxTrace.Trace("Found subscriptions for {0}", t.Name);
}
*/
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (_subscriptions.TryGetValue(messageType, out messageSubscriptions))
{
//MvxTrace.Trace("Found {0} messages of type {1}", messageSubscriptions.Values.Count, typeof(TMessage).Name);
toNotify = messageSubscriptions.Values.ToList();
}
}
if (toNotify == null || toNotify.Count == 0)
{
//Console.WriteLine("Nothing registered for messages of type {0}", messageType.Name);
return;
}
var allSucceeded = true;
foreach (var subscription in toNotify)
{
allSucceeded &= subscription.Invoke(message);
}
if (!allSucceeded)
{
//Console.WriteLine("One or more listeners failed - purge scheduled");
SchedulePurge(messageType);
}
}
public void RequestPurge(Type messageType)
{
SchedulePurge(messageType);
}
public void RequestPurgeAll()
{
lock (this)
{
SchedulePurge(_subscriptions.Keys.ToArray());
}
}
private readonly Dictionary<Type, bool> _scheduledPurges = new Dictionary<Type, bool>();
private void SchedulePurge(params Type[] messageTypes)
{
lock (this)
{
var threadPoolTaskAlreadyRequested = _scheduledPurges.Count > 0;
foreach (var messageType in messageTypes)
_scheduledPurges[messageType] = true;
if (!threadPoolTaskAlreadyRequested)
{
Task.Run(() => DoPurge());
}
}
}
private void DoPurge()
{
List<Type> toPurge = null;
lock (this)
{
toPurge = _scheduledPurges.Select(x => x.Key).ToList();
_scheduledPurges.Clear();
}
foreach (var type in toPurge)
{
PurgeMessagesOfType(type);
}
}
private void PurgeMessagesOfType(Type type)
{
lock (this)
{
Dictionary<Guid, BaseSubscription> messageSubscriptions;
if (!_subscriptions.TryGetValue(type, out messageSubscriptions))
{
return;
}
var deadSubscriptionIds = new List<Guid>();
foreach (var subscription in messageSubscriptions)
{
if (!subscription.Value.IsAlive)
{
deadSubscriptionIds.Add(subscription.Key);
}
}
//Console.WriteLine("Purging {0} subscriptions", deadSubscriptionIds.Count);
foreach (var id in deadSubscriptionIds)
{
messageSubscriptions.Remove(id);
}
PublishSubscriberChangeMessage(type, messageSubscriptions);
}
}
}
}