Skip to content

Commit

Permalink
Fix: Remove WeakReference (#4) and code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
sarweshkumar47 committed Aug 6, 2019
1 parent c026e14 commit 082c9c8
Showing 1 changed file with 19 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,17 @@
import com.makesense.labs.curvefit.utils.BezierCurveUtils;
import com.makesense.labs.curvefit.utils.Constants;

import java.lang.ref.WeakReference;
import java.util.List;

/**
* WorkerHandlerThread responsible for computing all intermediate points
* between two LatLng coordinates
*/

public final class WorkerHandlerThread extends HandlerThread {
public final class WorkerHandlerThread extends HandlerThread implements Handler.Callback {

private static Handler workerHandler;
private WeakReference<UiThreadCallback> uiThreadCallback;
private UiThreadCallback uiThreadCallback;

WorkerHandlerThread(String name) {
super(name);
Expand All @@ -53,39 +52,16 @@ public final class WorkerHandlerThread extends HandlerThread {
* Ui thread sends messages to the worker thread's message queue
*/
public void addMessage(Message message) {
getLooper();
if (workerHandler != null) {
workerHandler.sendMessage(message);
} else {
workerHandler = new Handler(getLooper(), this);
workerHandler.sendMessage(message);
}
}

public void setUiThreadCallback(UiThreadCallback callback) {
this.uiThreadCallback = new WeakReference<>(callback);
}

@Override
protected void onLooperPrepared() {
super.onLooperPrepared();

// Get a reference to worker thread's handler after looper is prepared
workerHandler = new Handler(getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

switch (msg.what) {
case Constants.TASK_START: {
MessageQueueData messageQueueData = (MessageQueueData) msg.obj;
CurveOptions options = computePoints(messageQueueData.getCurveOptions(),
messageQueueData.getProjection());
Message message = Message.obtain(null, Constants.TASK_COMPLETE, options);
/* Sends message back to Ui thread*/
uiThreadCallback.get().publishToUiThread(message);
break;
}
}
}
};
this.uiThreadCallback = callback;
}

/*
Expand Down Expand Up @@ -150,5 +126,18 @@ private void cleanupHandler() {
workerHandler = null;
}
}

@Override
public boolean handleMessage(Message msg) {
// Sends message back to Ui thread
if (msg.what == Constants.TASK_START) {
MessageQueueData messageQueueData = (MessageQueueData) msg.obj;
CurveOptions options = computePoints(messageQueueData.getCurveOptions(),
messageQueueData.getProjection());
Message message = Message.obtain(null, Constants.TASK_COMPLETE, options);
uiThreadCallback.publishToUiThread(message);
}
return false;
}
}

0 comments on commit 082c9c8

Please sign in to comment.