I'm working on an Android application that uses data from a server. I have a singleton Application object holding data that is used throughout the app (the User, its Addresses, etc.).
Until now, I was populating these data on the fly, ie. when I'm opening AddressesActivity, I call the addresses webService that populates data in Application before displaying the list.
However as the app grows and I need the same data in different places, I'm starting to duplicate code to populate the data. Plus I have to do checks all the time (if app.addresses == null callAddressesWebService, etc.).
I have some ideas to refactor this nicely, but I was wondering if there was a well-known pattern specifically for this particular issue?
EDIT
Here's what I started doing, any insight?
public abstract class LazyLoaded<T> {
private T localValue = null;
private boolean upToDate = false;
public void get(final SingleResultCallback<T> successCallback, final ErrorCallback errorCallback) {
if (getLocalValue() != null && isUpToDate()) {
successCallback.onResponse(getLocalValue());
}
else {
update(
new EmptyCallback() {
@Override
public void onResponse() {
get(successCallback, errorCallback);
}
},
errorCallback
);
}
}
protected abstract void update(EmptyCallback successCallback, ErrorCallback errorCallback);
protected T getLocalValue() {
return localValue;
}
protected void setLocalValue(T localValue) {
this.localValue = localValue;
this.upToDate = true;
}
protected boolean isUpToDate() {
return upToDate;
}
public void setObsolete() {
upToDate = false;
}
}
Aucun commentaire:
Enregistrer un commentaire