Skip to content

Instantly share code, notes, and snippets.

@adam-currie
Last active August 24, 2020 17:21
Show Gist options
  • Save adam-currie/6006e06880d37eea453a5d28de4a0d91 to your computer and use it in GitHub Desktop.
Save adam-currie/6006e06880d37eea453a5d28de4a0d91 to your computer and use it in GitHub Desktop.
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);
}
@adam-currie
Copy link
Author

userObserver.doIgnorantly(() -> { session.updateUserName("bob"); });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment