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