Skip to content

Instantly share code, notes, and snippets.

@billmote
Last active August 29, 2015 14:09
Show Gist options
  • Save billmote/0766aee32a62c198e776 to your computer and use it in GitHub Desktop.
Save billmote/0766aee32a62c198e776 to your computer and use it in GitHub Desktop.
Otto Bus wrapper that allows posting from any thread as well as unregistering without crashing for multiple calls to unregister.
public class EventBus {
private static final Handler mainThread = new Handler(Looper.getMainLooper());
private static EventBus mInstance;
private final Bus mBus;
@DebugLog
private EventBus() {
// Don't let this class get instantiated directly.
mBus = new Bus();
}
// @DebugLog intentionally omitted
private static EventBus getInstance() {
if (mInstance == null) {
mInstance = new EventBus();
}
return mInstance;
}
@DebugLog
public static void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
getInstance().mBus.post(event);
} else {
mainThread.post(new Runnable() {
@Override
public void run() {
post(event);
}
});
}
}
@DebugLog
public static void register(Object subscriber) {
getInstance().mBus.register(subscriber);
}
@DebugLog
public static void unregister(Object subscriber) {
try {
getInstance().mBus.unregister(subscriber);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment