1/*
2 * Copyright (C) 2007 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/**
18 * The EventBus allows publish-subscribe-style communication between components
19 * without requiring the components to explicitly register with one another
20 * (and thus be aware of each other).  It is designed exclusively to replace
21 * traditional Java in-process event distribution using explicit registration.
22 * It is <em>not</em> a general-purpose publish-subscribe system, nor is it
23 * intended for interprocess communication.
24 *
25 * <h2>One-Minute Guide</h2>
26 *
27 * Converting an existing EventListener-based system to use the EventBus is
28 * easy.
29 *
30 * <h3>For Listeners</h3>
31 * To listen for a specific flavor of event (say, a CustomerChangeEvent)...
32 * <ul>
33 * <li><strong>...in traditional Java events:</strong> implement an interface
34 *     defined with the event &mdash; such as CustomerChangeEventListener.</li>
35 * <li><strong>...with EventBus:</strong> create a method that accepts
36 *     CustomerChangeEvent as its sole argument, and mark it with the
37 *     {@link com.google.common.eventbus.Subscribe} annotation.</li>
38 * </ul>
39 *
40 * <p>To register your listener methods with the event producers...
41 * <ul>
42 * <li><strong>...in traditional Java events:</strong> pass your object to each
43 *     producer's {@code registerCustomerChangeEventListener} method.  These
44 *     methods are rarely defined in common interfaces, so in addition to
45 *     knowing every possible producer, you must also know its type.</li>
46 * <li><strong>...with EventBus:</strong> pass your object to the
47 *     {@link com.google.common.eventbus.EventBus#register(Object)} method on an
48 *     EventBus.  You'll need to
49 *     make sure that your object shares an EventBus instance with the event
50 *     producers.</li>
51 * </ul>
52 *
53 * <p>To listen for a common event supertype (such as EventObject or Object)...
54 * <ul>
55 * <li><strong>...in traditional Java events:</strong> not easy.</li>
56 * <li><strong>...with EventBus:</strong> events are automatically dispatched to
57 *     listeners of any supertype, allowing listeners for interface types
58 *     or "wildcard listeners" for Object.</li>
59 * </ul>
60 *
61 * <p>To listen for and detect events that were dispatched without listeners...
62 * <ul>
63 * <li><strong>...in traditional Java events:</strong> add code to each
64 *     event-dispatching method (perhaps using AOP).</li>
65 * <li><strong>...with EventBus:</strong> subscribe to {@link
66 *     com.google.common.eventbus.DeadEvent}.  The
67 *     EventBus will notify you of any events that were posted but not
68 *     delivered.  (Handy for debugging.)</li>
69 * </ul>
70 *
71 * <h3>For Producers</h3>
72 * To keep track of listeners to your events...
73 * <ul>
74 * <li><strong>...in traditional Java events:</strong> write code to manage
75 *     a list of listeners to your object, including synchronization, or use a
76 *     utility class like EventListenerList.</li>
77 * <li><strong>...with EventBus:</strong> EventBus does this for you.</li>
78 * </ul>
79 *
80 * <p>To dispatch an event to listeners...
81 * <ul>
82 * <li><strong>...in traditional Java events:</strong> write a method to
83 *     dispatch events to each event listener, including error isolation and
84 *     (if desired) asynchronicity.</li>
85 * <li><strong>...with EventBus:</strong> pass the event object to an EventBus's
86 *     {@link com.google.common.eventbus.EventBus#post(Object)} method.</li>
87 * </ul>
88 *
89 * <h2>Glossary</h2>
90 *
91 * The EventBus system and code use the following terms to discuss event
92 * distribution:
93 * <dl>
94 * <dt>Event</dt><dd>Any object that may be <em>posted</em> to a bus.</dd>
95 * <dt>Subscribing</dt><dd>The act of registering a <em>listener</em> with an
96 *     EventBus, so that its <em>handler methods</em> will receive events.</dd>
97 * <dt>Listener</dt><dd>An object that wishes to receive events, by exposing
98 *     <em>handler methods</em>.</dt>
99 * <dt>Handler method</dt><dd>A public method that the EventBus should use to
100 *     deliver <em>posted</em> events.  Handler methods are marked by the
101 *     {@link com.google.common.eventbus.Subscribe} annotation.</dd>
102 * <dt>Posting an event</dt><dd>Making the event available to any
103 *     <em>listeners</em> through the EventBus.</dt>
104 * </dl>
105 *
106 * <h2>FAQ</h2>
107 * <h3>Why must I create my own Event Bus, rather than using a singleton?</h3>
108 *
109 * The Event Bus doesn't specify how you use it; there's nothing stopping your
110 * application from having separate EventBus instances for each component, or
111 * using separate instances to separate events by context or topic.  This also
112 * makes it trivial to set up and tear down EventBus objects in your tests.
113 *
114 * <p>Of course, if you'd like to have a process-wide EventBus singleton,
115 * there's nothing stopping you from doing it that way.  Simply have your
116 * container (such as Guice) create the EventBus as a singleton at global scope
117 * (or stash it in a static field, if you're into that sort of thing).
118 *
119 * <p>In short, the EventBus is not a singleton because we'd rather not make
120 * that decision for you.  Use it how you like.
121 *
122 * <h3>Can I unregister a listener from the Event Bus?</h3>
123 * Currently, no -- a listener registered with an EventBus instance will
124 * continue to receive events until the EventBus itself is disposed.
125 *
126 * <p>In the apps using EventBus so far, this has not been a problem:
127 * <ul>
128 *   <li>Most listeners are registered on startup or lazy initialization, and
129 *       persist for the life of the application.
130 *   <li>Scope-specific EventBus instances can handle temporary event
131 *       distribution (e.g. distributing events among request-scoped objects)
132 *   <li>For testing, EventBus instances can be easily created and thrown away,
133 *       removing the need for explicit unregistration.
134 * </ul>
135 *
136 * <h3>Why use an annotation to mark handler methods, rather than requiring the
137 * listener to implement an interface?</h3>
138 * We feel that the Event Bus's {@code @Subscribe} annotation conveys your
139 * intentions just as explicitly as implementing an interface (or perhaps more
140 * so), while leaving you free to place event handler methods wherever you wish
141 * and give them intention-revealing names.
142 *
143 * <p>Traditional Java Events use a listener interface which typically sports
144 * only a handful of methods -- typically one.  This has a number of
145 * disadvantages:
146 * <ul>
147 *   <li>Any one class can only implement a single response to a given event.
148 *   <li>Listener interface methods may conflict.
149 *   <li>The method must be named after the event (e.g. {@code
150 *       handleChangeEvent}), rather than its purpose (e.g. {@code
151 *       recordChangeInJournal}).
152 *   <li>Each event usually has its own interface, without a common parent
153 *       interface for a family of events (e.g. all UI events).
154 * </ul>
155 *
156 * <p>The difficulties in implementing this cleanly has given rise to a pattern,
157 * particularly common in Swing apps, of using tiny anonymous classes to
158 * implement event listener interfaces.
159 *
160 * <p>Compare these two cases: <pre>
161 *   class ChangeRecorder {
162 *     void setCustomer(Customer cust) {
163 *       cust.addChangeListener(new ChangeListener() {
164 *         void customerChanged(ChangeEvent e) {
165 *           recordChange(e.getChange());
166 *         }
167 *       };
168 *     }
169 *   }
170 *
171 *   // Class is typically registered by the container.
172 *   class EventBusChangeRecorder {
173 *     &#064;Subscribe void recordCustomerChange(ChangeEvent e) {
174 *       recordChange(e.getChange());
175 *     }
176 *   }</pre>
177 *
178 * The intent is actually clearer in the second case: there's less noise code,
179 * and the event handler has a clear and meaningful name.
180 *
181 * <h3>What about a generic {@code Handler<T>} interface?</h3>
182 * Some have proposed a generic {@code Handler<T>} interface for EventBus
183 * listeners.  This runs into issues with Java's use of type erasure, not to
184 * mention problems in usability.
185 *
186 * <p>Let's say the interface looked something like the following: <pre>   {@code
187 *   interface Handler<T> {
188 *     void handleEvent(T event);
189 *   }}</pre>
190 *
191 * Due to erasure, no single class can implement a generic interface more than
192 * once with different type parameters.  This is a giant step backwards from
193 * traditional Java Events, where even if {@code actionPerformed} and {@code
194 * keyPressed} aren't very meaningful names, at least you can implement both
195 * methods!
196 *
197 * <h3>Doesn't EventBus destroy static typing and eliminate automated
198 * refactoring support?</h3>
199 * Some have freaked out about EventBus's {@code register(Object)} and {@code
200 * post(Object)} methods' use of the {@code Object} type.
201 *
202 * <p>{@code Object} is used here for a good reason: the Event Bus library
203 * places no restrictions on the types of either your event listeners (as in
204 * {@code register(Object)}) or the events themselves (in {@code post(Object)}).
205 *
206 * <p>Event handler methods, on the other hand, must explicitly declare their
207 * argument type -- the type of event desired (or one of its supertypes).  Thus,
208 * searching for references to an event class will instantly find all handler
209 * methods for that event, and renaming the type will affect all handler methods
210 * within view of your IDE (and any code that creates the event).
211 *
212 * <p>It's true that you can rename your {@code @Subscribed} event handler
213 * methods at will; Event Bus will not stop this or do anything to propagate the
214 * rename because, to Event Bus, the names of your handler methods are
215 * irrelevant.  Test code that calls the methods directly, of course, will be
216 * affected by your renaming -- but that's what your refactoring tools are for.
217 *
218 * <h3>What happens if I {@code register} a listener without any handler
219 * methods?</h3>
220 * Nothing at all.
221 *
222 * <p>The Event Bus was designed to integrate with containers and module
223 * systems, with Guice as the prototypical example.  In these cases, it's
224 * convenient to have the container/factory/environment pass <i>every</i>
225 * created object to an EventBus's {@code register(Object)} method.
226 *
227 * <p>This way, any object created by the container/factory/environment can
228 * hook into the system's event model simply by exposing handler methods.
229 *
230 * <h3>What Event Bus problems can be detected at compile time?</h3>
231 * Any problem that can be unambiguously detected by Java's type system.  For
232 * example, defining a handler method for a nonexistent event type.
233 *
234 * <h3>What Event Bus problems can be detected immediately at registration?</h3>
235 * Immediately upon invoking {@code register(Object)} , the listener being
236 * registered is checked for the <i>well-formedness</i> of its handler methods.
237 * Specifically, any methods marked with {@code @Subscribe} must take only a
238 * single argument.
239 *
240 * <p>Any violations of this rule will cause an {@code IllegalArgumentException}
241 * to be thrown.
242 *
243 * <p>(This check could be moved to compile-time using APT, a solution we're
244 * researching.)
245 *
246 * <h3>What Event Bus problems may only be detected later, at runtime?</h3>
247 * If a component posts events with no registered listeners, it <i>may</i>
248 * indicate an error (typically an indication that you missed a
249 * {@code @Subscribe} annotation, or that the listening component is not loaded).
250 *
251 * <p>(Note that this is <i>not necessarily</i> indicative of a problem.  There
252 * are many cases where an application will deliberately ignore a posted event,
253 * particularly if the event is coming from code you don't control.)
254 *
255 * <p>To handle such events, register a handler method for the {@code DeadEvent}
256 * class.  Whenever EventBus receives an event with no registered handlers, it
257 * will turn it into a {@code DeadEvent} and pass it your way -- allowing you to
258 * log it or otherwise recover.
259 *
260 * <h3>How do I test event listeners and their handler methods?</h3>
261 * Because handler methods on your listener classes are normal methods, you can
262 * simply call them from your test code to simulate the EventBus.
263 */
264package com.google.common.eventbus;
265