Fix websocket connection on refresh

On refresh the service was restarted but the connection
wasn't closed, therefore each incoming message was handled n times.
This commit is contained in:
Jannis Mattheis
2018-11-04 09:12:44 +01:00
parent ca0194e3bb
commit ee4d87113f
2 changed files with 14 additions and 3 deletions

View File

@@ -36,6 +36,7 @@ public class WebSocketConnection {
private BadRequestRunnable onBadRequest;
private OnFailureCallback onFailure;
private Runnable onReconnected;
private boolean isClosed;
WebSocketConnection(String baseUrl, String token) {
this.baseUrl = baseUrl;
@@ -84,6 +85,7 @@ public class WebSocketConnection {
public synchronized WebSocketConnection start() {
close();
isClosed = false;
Log.i("WebSocket: starting...");
webSocket = client.newWebSocket(request(), new Listener());
@@ -92,6 +94,8 @@ public class WebSocketConnection {
public synchronized void close() {
if (webSocket != null) {
Log.i("WebSocket: closing existing connection.");
isClosed = true;
webSocket.close(1000, "");
webSocket = null;
}
@@ -124,11 +128,13 @@ public class WebSocketConnection {
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
Log.w("WebSocket: closed");
synchronized (this) {
onClose.run();
if (!isClosed) {
Log.w("WebSocket: closed");
onClose.run();
}
}
super.onClosed(webSocket, code, reason);
}