Note: The client-side WAMP implementation is done using Autobahn.js, and promises are handled with when.js.
The goal is to establish a re-usable code structure where only one websocket 'session' or connection exists. Whenever a developer wants to subscribe to a topic using Autobahn, they should be able to do it using the existing connection object if it is already present; otherwise, a new one needs to be created.
The current issue arises when the connection already exists, requiring the use of setTimeout()
to ensure that it is indeed connected before duplicating the subscription code. This workaround approach is not ideal.
The following is the current code snippet:
(function() {
var connection = null;
subscribeTo('subject', __userId, __token, function(onconnect) {
console.log('Yay, connected');
});
function subscribeTo(subject, userId, token, onConnect, onDisconnect) {
if (connection === null)
{
connection = new ab.Session('ws://localhost:8080', function(onopen) {
connection.subscribe(JSON.stringify({subject: subject, userId: userId, token: token}), function(subscription, data) {
data = $.parseJSON(data);
// Perform actions with the received data ...
});
if (typeof onConnect === 'function') {
onConnect();
}
}, function(onclose) {
if (typeof onDisconnect === 'function') {
onDisconnect();
}
}, { 'skipSubprotocolCheck': true });
}
}
})();
An obstacle occurs when adding another subscribeTo()
immediately after the previous one. In this case, the connection is no longer null, but also not yet fully connected. Therefore, a setTimeout()
delay becomes necessary as shown below:
// Other subscribeTo calls at the top ...
subscribeTo('subject', __userId, __token, function(onconnect) {
console.log('Yay, connected');
});
subscribeTo('anothersubject', __userId, __token, function(onconnect) {
console.log('Yay, connected');
});
// The first call works, while the second requires a setTimeout() for the connection readiness
// Check if connection is not null...
} else {
setTimeout(function() {
connection.subscribe(topic... etc...) // Is there a better way?
}, 1000);
}
Eliminating the setTimeout()
results in an error stating "Autbahn is not connected".
Is there a more efficient way to maintain a single, reusable connection without resorting to code duplication, or should I accept creating a new connection for each subscription due to the promise handling? Maybe leveraging promises could provide a solution here, although my familiarity with them is limited.