Skip to content

Commit

Permalink
fix(state channels): wait for connection to be established before sen…
Browse files Browse the repository at this point in the history
…ding generic message (#723)

* feat(state channels): add .off method

* fix(state channels): wait for connection to be established before sending generic message
  • Loading branch information
mpowaga authored and nduchak committed Nov 11, 2019
1 parent ae4426e commit c5f35d1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
30 changes: 29 additions & 1 deletion es/channel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ function on (event, callback) {
eventEmitters.get(this).on(event, callback)
}

/**
* Remove event listener function
*
* @param {String} event - Event name
* @param {Function} callback - Callback function
*/
function off (event, callback) {
eventEmitters.get(this).removeListener(event, callback)
}

/**
* Close the connection
*/
Expand Down Expand Up @@ -659,7 +669,24 @@ function sendMessage (message, recipient) {
if (typeof message === 'object') {
info = JSON.stringify(message)
}
send(this, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } })
const doSend = (channel) => send(channel, {
jsonrpc: '2.0',
method: 'channels.message',
params: { info, to: recipient }
})
if (this.status() === 'connecting') {
const onStatusChanged = (status) => {
if (status !== 'connecting') {
// For some reason we can't immediately send a message when connection is
// established established. Thus we wait 500ms which seems to work.
setTimeout(() => doSend(this), 500)
this.off('statusChanged', onStatusChanged)
}
}
this.on('statusChanged', onStatusChanged)
} else {
doSend(this)
}
}

async function reconnect (options, txParams) {
Expand Down Expand Up @@ -724,6 +751,7 @@ const Channel = AsyncInit.compose({
},
methods: {
on,
off,
status,
state,
id,
Expand Down
1 change: 1 addition & 0 deletions es/channel/internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ async function initialize (channel, channelOptions) {
eventEmitters.set(channel, new EventEmitter())
sequence.set(channel, 0)
rpcCallbacks.set(channel, new Map())
changeStatus(channel, 'connecting')
const ws = await WebSocket(wsUrl, {
onopen: () => {
changeStatus(channel, 'connected')
Expand Down

0 comments on commit c5f35d1

Please sign in to comment.