-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReactiveExtensionsEventBroker.java
71 lines (59 loc) · 1.51 KB
/
ReactiveExtensionsEventBroker.java
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
/*
Mediator - event broker implementing reactive extensions
*/
package behavioral.mediator;
import io.reactivex.Observable;
import io.reactivex.Observer;
import java.util.ArrayList;
import java.util.List;
class EventBroker extends Observable<Integer>
{
private List<Observer<? super Integer>>
observers = new ArrayList<>();
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
observers.add(observer);
}
// utility method
public void publish(int n)
{
for(Observer<? super Integer> o : observers)
o.onNext(n); // reactor extensions pipeline method
}
}
class FootballPlayer
{
private int goalsScored = 0;
private EventBroker broker;
public String name;
public FootballPlayer(EventBroker broker, String name) {
this.broker = broker;
this.name = name;
}
public void score()
{
broker.publish(++goalsScored);
}
}
class FootballCoach
{
public FootballCoach(EventBroker broker)
{
// subscribes to any event in the event broker
broker.subscribe(i ->
System.out.println("Hey, you scored "
+ i + " goals!")
);
}
}
class EventBrokerDemo
{
public static void main(String[] args) {
EventBroker broker = new EventBroker();
FootballPlayer player = new FootballPlayer(broker, "jones");
FootballCoach coach = new FootballCoach(broker);
player.score();
player.score();
player.score();
}
}