Skip to content

Instantly share code, notes, and snippets.

@ilkinulas
Created April 17, 2016 17:42
Show Gist options
  • Save ilkinulas/f7ef529cc07a6b3a867f1a8f04db0213 to your computer and use it in GitHub Desktop.
Save ilkinulas/f7ef529cc07a6b3a867f1a8f04db0213 to your computer and use it in GitHub Desktop.
CountDownTimer with WeakReferences
package codekata.observer;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
public class CountDownTimer {
private static long ONE_SECOND = 1000L;
private long countDownMillis;
private long elapsedTimeSinceLastTick;
private long totalElapsedTime;
private List<WeakReference<CountDownObserver>> observers = new LinkedList<>();
public CountDownTimer(long initialValue) {
this.countDownMillis = initialValue;
}
//Called every frame
public void update(long deltaTime) {
if (isFinished()) {
return;
}
if (totalElapsedTime == 0) {
notifyStart();
}
totalElapsedTime += deltaTime;
elapsedTimeSinceLastTick += deltaTime;
if (elapsedTimeSinceLastTick >= ONE_SECOND) {
elapsedTimeSinceLastTick = 0;
notifyCountDown();
}
if (isFinished()) {
notifyCountDown();
notifyFinish();
}
}
private boolean isFinished() {
return totalElapsedTime >= countDownMillis;
}
private void notifyCountDown() {
for(WeakReference<CountDownObserver> ref : this.observers) {
CountDownObserver observer = ref.get();
if (observer != null) {
observer.onCountDown(
totalElapsedTime,
Math.max(0, (countDownMillis - totalElapsedTime)));
} else {
System.out.println("!!! DELETED");
}
}
}
private void notifyStart() {
for(WeakReference<CountDownObserver> ref : this.observers) {
CountDownObserver observer = ref.get();
if (observer != null) {
observer.onStart();
}
}
}
private void notifyFinish() {
for(WeakReference<CountDownObserver> ref : this.observers) {
CountDownObserver observer = ref.get();
if (observer != null) {
observer.onFinish();
}
}
}
public void registerObserver(CountDownObserver observer) {
WeakReference<CountDownObserver> weakReference = findWeakReference(observer);
if (weakReference == null) {
weakReference = new WeakReference<>(observer);
this.observers.add(weakReference);
}
}
public void unregisterObserver(CountDownObserver observer) {
WeakReference<CountDownObserver> weakReference = findWeakReference(observer);
if (weakReference != null) {
this.observers.remove(weakReference);
}
}
private WeakReference<CountDownObserver> findWeakReference(CountDownObserver observer) {
WeakReference<CountDownObserver> weakReference = null;
for(WeakReference<CountDownObserver> ref : this.observers) {
if (ref.get() == observer) {
weakReference = ref;
}
}
return weakReference;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment