Created
June 8, 2016 05:31
-
-
Save mindwing/d2805441c54d801537ba46d7b6b728d8 to your computer and use it in GitHub Desktop.
Agera Explained - 08.Incrementally Agerifying legacy code
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 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