Skip to content

Commit c5f35d1

Browse files
mpowaganduchak
authored andcommitted
fix(state channels): wait for connection to be established before sending generic message (#723)
* feat(state channels): add .off method * fix(state channels): wait for connection to be established before sending generic message
1 parent ae4426e commit c5f35d1

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

es/channel/index.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,16 @@ function on (event, callback) {
6565
eventEmitters.get(this).on(event, callback)
6666
}
6767

68+
/**
69+
* Remove event listener function
70+
*
71+
* @param {String} event - Event name
72+
* @param {Function} callback - Callback function
73+
*/
74+
function off (event, callback) {
75+
eventEmitters.get(this).removeListener(event, callback)
76+
}
77+
6878
/**
6979
* Close the connection
7080
*/
@@ -659,7 +669,24 @@ function sendMessage (message, recipient) {
659669
if (typeof message === 'object') {
660670
info = JSON.stringify(message)
661671
}
662-
send(this, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } })
672+
const doSend = (channel) => send(channel, {
673+
jsonrpc: '2.0',
674+
method: 'channels.message',
675+
params: { info, to: recipient }
676+
})
677+
if (this.status() === 'connecting') {
678+
const onStatusChanged = (status) => {
679+
if (status !== 'connecting') {
680+
// For some reason we can't immediately send a message when connection is
681+
// established established. Thus we wait 500ms which seems to work.
682+
setTimeout(() => doSend(this), 500)
683+
this.off('statusChanged', onStatusChanged)
684+
}
685+
}
686+
this.on('statusChanged', onStatusChanged)
687+
} else {
688+
doSend(this)
689+
}
663690
}
664691

665692
async function reconnect (options, txParams) {
@@ -724,6 +751,7 @@ const Channel = AsyncInit.compose({
724751
},
725752
methods: {
726753
on,
754+
off,
727755
status,
728756
state,
729757
id,

es/channel/internal.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ async function initialize (channel, channelOptions) {
225225
eventEmitters.set(channel, new EventEmitter())
226226
sequence.set(channel, 0)
227227
rpcCallbacks.set(channel, new Map())
228+
changeStatus(channel, 'connecting')
228229
const ws = await WebSocket(wsUrl, {
229230
onopen: () => {
230231
changeStatus(channel, 'connected')

0 commit comments

Comments
 (0)