Last active
August 29, 2015 00:59
-
-
Save wesleybliss/785deab2fc495a597526 to your computer and use it in GitHub Desktop.
Example Otto Event Bus Provider
This file contains 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
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