Last active
August 24, 2020 17:21
-
-
Save adam-currie/6006e06880d37eea453a5d28de4a0d91 to your computer and use it in GitHub Desktop.
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.arch.lifecycle.Observer; | |
import android.support.annotation.Nullable; | |
public abstract class IgnorantObserver<T> implements Observer<T>{ | |
private boolean isIgnoring = false; | |
private boolean doingIgnorantly = false; | |
public IgnorantObserver(){ | |
this(false); | |
} | |
public IgnorantObserver(boolean isIgnoring){ | |
this.isIgnoring = isIgnoring; | |
} | |
@Override | |
public final void onChanged(@Nullable T t) { | |
if((!isIgnoring)&&(!doingIgnorantly)) ignorantOnChanged(t); | |
} | |
public final void ignore(boolean ignore){ | |
isIgnoring = ignore; | |
} | |
/** | |
* returns false when executing doIgnorantly even if underling value is true | |
* use isUnderlyingIgnoring() instead for that | |
*/ | |
public final boolean isIgnoring(){ | |
return isIgnoring && !doingIgnorantly; | |
} | |
public final boolean isUnderlingIgnoring(){ | |
return isIgnoring; | |
} | |
/** | |
* execute and ignore all onChanged events for this observer while running | |
* calls to ignore will not take effect until this returns | |
*/ | |
public final void doIgnorantly(Function f){ | |
boolean isNestedDoIgnorantly = doingIgnorantly; | |
doingIgnorantly = true; | |
f.run(); | |
doingIgnorantly = isNestedDoIgnorantly; | |
} | |
public interface Function{ public void run();} | |
/** | |
* called by onChanged only when not ignoring | |
*/ | |
protected abstract void ignorantOnChanged(@Nullable T t); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
userObserver.doIgnorantly(() -> { session.updateUserName("bob"); });