From b5ea5a2c4d053cc0962305a7b4f834c28f6d8ddf Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Wed, 2 Nov 2022 10:24:56 -0700 Subject: [PATCH] Fix WebSocketModule not closing connections on reload Summary: Saw in the logs an ever increasing number of warnings coming from WebSocketModule about requesting an instance that has already gone away. On module invalidation we should close all outstanding websockets, as they will no longer be able to send events to JS. Changelog: [Android][Fixed] On instance destroy, websockets are correctly closed Reviewed By: mdvacca Differential Revision: D40897255 fbshipit-source-id: 1578de8baa342479d14ee1070c3314d45c7fbd8d --- .../react/modules/websocket/WebSocketModule.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java index 92e5b9143b3..50e6f9d84c3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java @@ -58,10 +58,18 @@ public final class WebSocketModule extends NativeWebSocketModuleSpec { mCookieHandler = new ForwardingCookieHandler(context); } - private void sendEvent(String eventName, WritableMap params) { - ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); + @Override + public void invalidate() { + for (WebSocket socket : mWebSocketConnections.values()) { + socket.close(1001 /* endpoint is going away */, null); + } + mWebSocketConnections.clear(); + mContentHandlers.clear(); + } - if (reactApplicationContext != null) { + private void sendEvent(String eventName, WritableMap params) { + ReactApplicationContext reactApplicationContext = getReactApplicationContext(); + if (reactApplicationContext.hasActiveReactInstance()) { reactApplicationContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params);