Skip to content

Instantly share code, notes, and snippets.

@Orange168
Created September 3, 2018 13:09
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 Orange168/434df3bd755ad590e973e33c8bd0e38e to your computer and use it in GitHub Desktop.
Save Orange168/434df3bd755ad590e973e33c8bd0e38e to your computer and use it in GitHub Desktop.
[主线程运行] #RxJava
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