com.stanfy.enroscar.async.internal.ObserverBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of enroscar-content Show documentation
Show all versions of enroscar-content Show documentation
Helper classes and extended abstractions for Android loaders, content resolvers, and DB access.
package com.stanfy.enroscar.async.internal;
import com.stanfy.enroscar.async.Action;
import com.stanfy.enroscar.async.AsyncError;
import com.stanfy.enroscar.async.AsyncObserver;
/**
* @author Roman Mazur - Stanfy (http://stanfy.com)
*/
public final class ObserverBuilder {
/** Building target. */
private final T description;
/** Observer instance. */
private final Observer observer = new Observer<>();
public ObserverBuilder(final int loaderId, final T description) {
this.description = description;
this.description.addObserver(loaderId, observer);
}
public ObserverBuilder doOnResult(final Action resultAction) {
observer.resultAction = resultAction;
return this;
}
public ObserverBuilder doOnError(final Action errorAction) {
observer.errorAction = errorAction;
return this;
}
public T alsoWhen() {
return description;
}
/**
* {@link AsyncObserver} based on {@link Action}s.
* @param data type
*/
private static class Observer implements AsyncObserver {
/** On result. */
Action resultAction;
/** On error. */
Action errorAction;
@Override
public void onError(final Throwable e) {
if (errorAction != null) {
errorAction.act(e);
} else {
throw new AsyncError(e);
}
}
@Override
public void onResult(final D data) {
if (resultAction != null) {
resultAction.act(data);
}
}
}
}