Created
September 3, 2018 13:09
-
-
Save Orange168/434df3bd755ad590e973e33c8bd0e38e to your computer and use it in GitHub Desktop.
[主线程运行] #RxJava
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
public abstract class MainThreadDisposable implements Disposable { | |
/** | |
* Verify that the calling thread is the Android main thread. | |
* <p> | |
* 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. | |
*/ | |
public static void verifyMainThread() { | |
if (Looper.myLooper() != Looper.getMainLooper()) { | |
throw new IllegalStateException( | |
"Expected to be called on the main thread but was " + Thread.currentThread().getName()); | |
} | |
} | |
private final AtomicBoolean unsubscribed = new AtomicBoolean(); | |
@Override | |
public final boolean isDisposed() { | |
return unsubscribed.get(); | |
} | |
@Override | |
public final void dispose() { | |
if (unsubscribed.compareAndSet(false, true)) { | |
if (Looper.myLooper() == Looper.getMainLooper()) { | |
onDispose(); | |
} else { | |
AndroidSchedulers.mainThread().scheduleDirect(new Runnable() { | |
@Override public void run() { | |
onDispose(); | |
} | |
}); | |
} | |
} | |
} | |
protected abstract void onDispose(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment