Do you want to request a feature or report a bug?
bug
What is the current behavior?
WebSocket closed when closing a subscription and then creating a new subscription immediately
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.
Say we have two react component subscribed to different query. If we navigate from one to another,
WebSocket will be closed.
What is the expected behavior?
The previous subscription should be disconnected and the new one connected. The WebSocket should be always on.
Which versions and which environment (browser, react-native, nodejs) / OS are affected by this issue? Did this work in previous versions?
Chrome Version 78.0.3904.108
I think the problem is here:
https://github.com/awslabs/aws-mobile-appsync-sdk-js/pull/484/files#diff-50358c204dd1dc3704f01f2d4b019000R184
It closed the WebSocket in a timeout, while in this period of time this.subscriptionObserverMap.size can be nonzero again. (another subscription)
I ran across this the same issue today. As a workaround, I used a timeout to skip creating the subscription until two seconds after mounting to prevent the second subscription from getting attached to the closed WebSocket and force it to a new connection. Although not ideal, this seems to prevent the issue from happening. Posting this here in case anyone else runs into a similar situation.
const gqlSubscription = gql`
// subscription query goes here
`
const [delaySub, setDelaySub] = useState(true);
useEffect(() => {
let delayTimeoutId = window.setTimeout(() => {
setDelaySub(false);
delayTimeoutId = undefined;
}, 2000);
return () => {
if (delayTimeoutId) {
window.clearTimeout(delayTimeoutId);
}
};
}, []);
return useSubscription(gqlSubscription, {
skip: delaySub,
});
Most helpful comment
I ran across this the same issue today. As a workaround, I used a timeout to
skipcreating the subscription until two seconds after mounting to prevent the second subscription from getting attached to the closed WebSocket and force it to a new connection. Although not ideal, this seems to prevent the issue from happening. Posting this here in case anyone else runs into a similar situation.