-
Notifications
You must be signed in to change notification settings - Fork 7
/
ShowCase.cs
111 lines (88 loc) · 2.75 KB
/
ShowCase.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
using System;
using System.Threading.Tasks;
using libc.eventbus.System;
using libc.eventbus.Types;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace libc.eventbus.tests;
[TestClass]
public class Showcase
{
[TestMethod]
public void Showcase_WithoutCatchAll()
{
// 1- create an event bus
var bus = new DefaultEventBus();
// 2- subscribe to SimpleMessage event via PrintMessageRaw event handler
bus.Subscribe<SimpleMessage, PrintMessageRaw>(new PrintMessageRaw());
// 3- subscribe to SimpleMessage event via PrintMessagePretty event handler
var x = new PrintMessagePretty();
bus.Subscribe<SimpleMessage, PrintMessagePretty>(x);
// 4- remember subscribing to a message with the same handler instance, has no effect!
bus.Subscribe<SimpleMessage, PrintMessagePretty>(x);
// 5- create the event
var message = new SimpleMessage("a simple message");
// 6- publish the event
bus.Publish(message);
}
[TestMethod]
public void Showcase_WithCatchAll()
{
// 1- create an event bus
var bus = new DefaultEventBus();
// 2- subscribe to SimpleMessage event via PrintMessageRaw event handler
bus.Subscribe<SimpleMessage, PrintMessageRaw>(new PrintMessageRaw());
// 3- subscribe to SimpleMessage event via PrintMessagePretty event handler
bus.Subscribe<SimpleMessage, PrintMessagePretty>(new PrintMessagePretty());
// 4- register a catch-all event handler
bus.RegisterCatchAllHandler(new CatchAllMessages());
// 5- create the event
var message = new SimpleMessage("a simple message");
// 6- publish the event
bus.Publish(message);
}
public class SimpleMessage : IEvent
{
public SimpleMessage(string text)
{
Text = text;
}
public string Text { get; }
}
public class PrintMessageRaw : IEventHandler<SimpleMessage>
{
public Task Handle(SimpleMessage ev)
{
// print message
Console.WriteLine($"Raw: {ev.Text}");
return Task.CompletedTask;
}
}
public class PrintMessagePretty : IEventHandler<SimpleMessage>
{
public Task Handle(SimpleMessage ev)
{
// print message
Console.WriteLine($"Pretty: {ev.Text}");
return Task.CompletedTask;
}
}
public class PrivateMessage : IEvent
{
public PrivateMessage(string secret)
{
Secret = secret;
}
public string Secret { get; private set; }
}
public class CatchAllMessages : ICatchAllEventHandler
{
public Task Handle(IEvent ev)
{
if (ev is SimpleMessage)
Console.WriteLine($"Caught SimpleMessage: {(ev as SimpleMessage).Text}");
else if (ev is PrivateMessage)
Console.WriteLine($"Caught PrivateMessage: {(ev as PrivateMessage).Secret}");
return Task.CompletedTask;
}
}
}