Skip to content

Instantly share code, notes, and snippets.

@ntakouris
Created May 13, 2018 18:18
Show Gist options
  • Save ntakouris/086697fbbdcf993ce9eff8ffdf437ef9 to your computer and use it in GitHub Desktop.
Save ntakouris/086697fbbdcf993ce9eff8ffdf437ef9 to your computer and use it in GitHub Desktop.
HashMap<String,PedestalledLeanLinkedList<BooleanContradictableType>> requestsInProgress = new HashMap<>();
protected synchronized void likeDislike(String id, boolean _desiredLikeState, boolean chain) {
PedestalledLeanLinkedList<BooleanContradictableType> currentLinkedList = requestsInProgress.get(id);
if (chain && currentLinkedList != null) {
currentLinkedList.poll();/* Previous like state request */
if (currentLinkedList.isEmpty()) {
requestsInProgress.remove(id);
return;
}
} else {
if (currentLinkedList == null) {
currentLinkedList = new PedestalledLeanLinkedList<>();
currentLinkedList.insert(new BooleanContradictableType(_desiredLikeState));
requestsInProgress.put(id, currentLinkedList);
} else {
BooleanContradictableType type = currentLinkedList.peek();
if (type != null && type.getValue() == _desiredLikeState) {
return;
}
currentLinkedList.insert(new BooleanContradictableType(_desiredLikeState));
}
}
BooleanContradictableType type = currentLinkedList.peek();
boolean desiredLikeState = type.getValue();
executors.networkIO().execute(() -> {
Runnable keepTheChainGoing = () -> likeDislike(id, desiredLikeState, true);
final Response currentForLike = sourceOfTruth.find(id);
if (currentForLike.isLiked() == desiredLikeState) {
keepTheChainGoing.run();
return;
}
currentForLike.setLiked(desiredLikeState);
currentForLike.setLikes(desiredLikeState ? currentForLike.getLikes() + 1 : currentForLike.getLikes() - 1);
sourceOfTruth.update(currentForLike);
ResponseBodyCallbackAdapter callbackAdapter = new ResponseBodyCallbackAdapter<>(new ResponseBodyCallbackAdapter.SimpleCallback<Void>() {
@Override
public void onSuccessfulResponse(Void response) {
sourceOfTruth.update(currentForLike);
}
@Override
public void onNoSuccess() {
revertLikeDislike();
}
@Override
public void onPostEverytime() {
keepTheChainGoing.run();
}
private void revertLikeDislike() {
if (desiredLikeState) {
currentForLike.dislike();
} else {
currentForLike.like();
}
sourceOfTruth.update(currentForLike);
}
});
Call<ResponseBody<Void>> call = desiredLikeState ?
apiCalls.like(id) : apiCalls.unlike(id);
call.enqueue(callbackAdapter);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment