Skip to content

Instantly share code, notes, and snippets.

@jpotts18
Created January 13, 2015 00:01
Show Gist options
  • Save jpotts18/be6949422d67113a2801 to your computer and use it in GitHub Desktop.
Save jpotts18/be6949422d67113a2801 to your computer and use it in GitHub Desktop.
public class PostFromAnyThreadBus extends Bus {
private static PostFromAnyThreadBus instance;
public synchronized static PostFromAnyThreadBus getInstance() {
if (instance == null){
instance = new PostFromAnyThreadBus();
}
return instance;
}
private PostFromAnyThreadBus()
{
super(ThreadEnforcer.MAIN);
}
@Override
public void post(final Object event)
{
if (Looper.myLooper() != Looper.getMainLooper())
{
// We're not in the main loop, so we need to get into it.
(new Handler(Looper.getMainLooper())).post(new Runnable()
{
@Override
public void run()
{
// We're now in the main loop, we can post now
PostFromAnyThreadBus.super.post(event);
}
});
}
else
{
super.post(event);
}
}
@Override
public void unregister(final Object object)
{
// Lots of edge cases with register/unregister that sometimes throw.
try
{
super.unregister(object);
}
catch (IllegalArgumentException e)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment