Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Base Loader for Android
public abstract class BaseLoader<T> {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
isNotReady = false;
isError = false;
isRunning = true;
}
@Override
@Nullable
protected Void doInBackground(Void... params) {
try {
lastResult = load();
} catch (RuntimeException e) {
lastResult = null;
isError = true;
isNotReady = false;
}
isRunning = false;
return null;
}
@Override
protected void onPostExecute(Void result) {
deliverResults();
}
};
private void deliverResults() {
if (isError) {
onLoadError();
}
if (!isNotReady) {
onDataLoaded(lastResult);
}
}
private T lastResult;
private volatile boolean isNotReady;
private volatile boolean isError;
private volatile boolean isRunning;
private final Set<Class<?>> observedModels;
protected abstract T load();
public BaseLoader() {
observedModels = observedModels();
}
public void reload() {
start(true);
}
public void start() {
TeacherApp.bus().register(this);
start(false);
}
private void start(boolean forceReload) {
if (forceReload) {
task.cancel(false);
task.execute();
} else if (lastResult == null) {
if (!isRunning) {
task.execute();
}
} else {
deliverResults();
}
}
public void unregister() {
TeacherApp.bus().unregister(this);
}
public abstract void onDataLoaded(@Nullable T data);
protected abstract void onLoadError();
protected Set<Class<?>> observedModels() {
return Collections.emptySet();
}
@Subscribe
public void onModelUpdate(ModelUpdate modelUpdate) {
if (observedModels.contains(modelUpdate.modelClass)) {
reload();
}
}
protected void setLoadError() {
isError = true;
}
protected void setNotReady() {
isNotReady = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.