Skip to content

Instantly share code, notes, and snippets.

@mindwing
Created June 8, 2016 05:31
Show Gist options
  • Save mindwing/d2805441c54d801537ba46d7b6b728d8 to your computer and use it in GitHub Desktop.
Save mindwing/d2805441c54d801537ba46d7b6b728d8 to your computer and use it in GitHub Desktop.
Agera Explained - 08.Incrementally Agerifying legacy code
public class AsyncOperatorRepository<P, R> extends BaseObservable
implements Repository<Result<R>>, Callback<R>, Updatable {
private final AsyncOperator<P, R> asyncOperator;
private final Repository<P> paramRepository;
private Result<R> result;
private Cancellable cancellable;
public AsyncOperatorRepository(AsyncOperator<P, R> asyncOperator,
Repository<P> paramRepository) {
this.asyncOperator = asyncOperator;
this.paramRepository = paramRepository;
this.result = Result.absent();
}
@Override
protected void observableActivated() {
paramRepository.addUpdatable(this);
update();
}
@Override
protected synchronized void observableDeactivated() {
paramRepository.removeUpdatable(this);
cancelOngoingRequestLocked();
}
@Override
public synchronized void update() {
cancelOngoingRequestLocked();
// Adapt accordingly if paramRepository supplies a Result.
cancellable = asyncOperator.request(paramRepository.get(), this);
}
private void cancelOngoingRequestLocked() {
if (cancellable != null) {
cancellable.cancel();
cancellable = null;
}
}
@Override
public synchronized void onResponse(R response) {
cancellable = null;
result = Result.absentIfNull(response);
dispatchUpdate();
}
// Similar process for fallible requests (typically with an
// onError(Throwable) callback): wrap the failure in a Result and
// dispatchUpdate().
@Override
public synchronized Result<R> get() {
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment