Created
December 11, 2015 21:04
-
-
Save nbarraille/7dd5ab88e01240389e3c to your computer and use it in GitHub Desktop.
Base Loader for Android
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
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