Class MainThreadSubscription

  • All Implemented Interfaces:
    Subscription


    public abstract class MainThreadSubscription
    extends Object
    implements Subscription
    A subscription which ensures its unsubscribe action is executed on the main thread. When unsubscription occurs on a different thread than the main thread, the action is posted to run on the main thread as soon as possible.

    Instances of this class are useful in creating observables which interact with APIs that can only be used on the main thread, such as UI objects.

    A convenience method is also provided for validating whether code is being called on the main thread. Calls to this method along with instances of this class are commonly used when creating custom observables using the following pattern:

     &#064;Override public void call(Subscriber<? extends T> subscriber) { MainThreadSubscription.verifyMainThread(); // TODO set up behavior subscriber.add(new MainThreadSubscriber() { &#064;Override public void onUnsubscribe() { // TODO undo behavior } }); } 
    • Constructor Detail

      • MainThreadSubscription

        public MainThreadSubscription()
    • Method Detail

      • verifyMainThread

        public static void verifyMainThread()
        Verify that the calling thread is the Android main thread.

        Calls to this method are usually preconditions for subscription behavior which instances of this class later undo. See the class documentation for an example.

        Throws:
        IllegalStateException - when called from any other thread.
      • isUnsubscribed

        public final boolean isUnsubscribed()
      • unsubscribe

        public final void unsubscribe()
      • onUnsubscribe

        protected abstract void onUnsubscribe()