Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Last active August 29, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleybliss/785deab2fc495a597526 to your computer and use it in GitHub Desktop.
Save wesleybliss/785deab2fc495a597526 to your computer and use it in GitHub Desktop.
Example Otto Event Bus Provider
package com.foo.bar.utils;
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
/**
* Maintains a singleton instance for obtaining the bus. Ideally this would be replaced with a more efficient means such as through
* injection directly into interested classes.
*/
public final class BusProvider {
private static final MainPostingBus BUS = new MainPostingBus();
public static MainPostingBus getInstance() {
return BUS;
}
private BusProvider() {}
public static class MainPostingBus extends Bus {
private final Handler mainThread = new Handler( Looper.getMainLooper() );
public MainPostingBus() {
super( ThreadEnforcer.ANY );
}
@Override
public void post( final Object event ) {
if ( Looper.myLooper() == Looper.getMainLooper() ) {
super.post( event );
}
else {
mainThread.post( new Runnable() {
@Override
public void run() {
post( event );
}
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment