Last active
August 29, 2015 14:09
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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