Skip to content

Commit 92b50c4

Browse files
authored
fix: Port over Amplify fix for subscription race conditions (#509) (#704)
1 parent f5c6e1a commit 92b50c4

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

packages/aws-appsync-subscription-link/src/realtime-subscription-handshake-link.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -199,22 +199,26 @@ export class AppSyncRealTimeSubscriptionHandshakeLink extends ApolloLink {
199199

200200
private _removeSubscriptionObserver(subscriptionId) {
201201
this.subscriptionObserverMap.delete(subscriptionId);
202-
if (this.subscriptionObserverMap.size === 0) {
203-
// Socket could be sending data to unsubscribe so is required to wait until is flushed
204-
this._closeSocketWhenFlushed();
205-
}
202+
// Verifying for 1000ms after removing subscription in case there are new subscriptions on mount / unmount
203+
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
206204
}
207205

208-
private _closeSocketWhenFlushed() {
209-
logger("closing WebSocket...");
210-
clearTimeout(this.keepAliveTimeoutId);
206+
private _closeSocketIfRequired() {
207+
if (this.subscriptionObserverMap.size > 0) {
208+
// There are active subscriptions on the WebSocket
209+
return;
210+
}
211+
211212
if (!this.awsRealTimeSocket) {
212213
this.socketStatus = SOCKET_STATUS.CLOSED;
213214
return;
214215
}
215216
if (this.awsRealTimeSocket.bufferedAmount > 0) {
216-
setTimeout(this._closeSocketWhenFlushed.bind(this), 1000);
217+
// There is still data on the WebSocket
218+
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
217219
} else {
220+
logger("closing WebSocket...");
221+
clearTimeout(this.keepAliveTimeoutId);
218222
const tempSocket = this.awsRealTimeSocket;
219223
tempSocket.close(1000);
220224
this.awsRealTimeSocket = null;

0 commit comments

Comments
 (0)