Last active
June 29, 2017 13:17
-
-
Save chris-carneiro/7799f247df082ff25d2b856982b908a0 to your computer and use it in GitHub Desktop.
Init EventBus singleton class for Otto library
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
| import android.os.Handler; | |
| import android.os.Looper; | |
| import com.squareup.otto.Bus; | |
| /** | |
| * 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. | |
| * <p> | |
| * Created by ChrisC on 17/05/17. | |
| */ | |
| public final class MainThreadBus extends Bus { | |
| private final Handler mHandler = new Handler(Looper.getMainLooper()); | |
| @Override | |
| public void post(final Object event) { | |
| if (Looper.myLooper() == Looper.getMainLooper()) { | |
| super.post(event); | |
| } else { | |
| mHandler.post(new Runnable() { | |
| @Override | |
| public void run() { | |
| MainThreadBus.super.post(event); | |
| } | |
| }); | |
| } | |
| } | |
| /** | |
| * Create a singleton | |
| */ | |
| public enum EventBus { | |
| INSTANCE; | |
| private static final MainThreadBus bus = new MainThreadBus(); | |
| /** | |
| * Get the instance of {@link Bus} class. <BR /> | |
| * Use this bus to communicate between registered objects. | |
| * | |
| * @return Bus object | |
| */ | |
| public MainThreadBus get() { | |
| return EventBus.bus; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment