Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deferred emission of stream events received before emitting connect event #26

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,27 @@ WebRTCSwarm.prototype.close = function (cb) {
}

function setup (swarm, peer, id) {
var delayedStreams = [];

peer.on('stream', function onStreamWhileNotConnected (stream) {
debug('peer', id, 'is', (peer.connected ? '' : 'not ') + 'connected')
if (peer.connected) {
peer.removeListener('stream', onStreamWhileNotConnected)
} else {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather return early than use else.

debug('on stream while peer', id, 'not connected', stream)
delayedStreams.push(stream)
}
})

peer.on('connect', function () {
debug('connected to peer', id)
swarm.peers.push(peer)
swarm.emit('peer', peer, id)
swarm.emit('connect', peer, id)
delayedStreams.forEach(function (stream) {
peer.emit('stream', stream)
})
delayedStreams = [];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rather clean up in line 75 together with the removal of the listener.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I move this to line 75, the array will be only freed in case of receiving a stream after connecting. Actually, this cleaning is incomplete, I should remove also the event listener to avoid memory leaks and nullify the array. I'll do in the following commit.

})

var onclose = once(function (err) {
Expand Down Expand Up @@ -135,7 +151,6 @@ function subscribe (swarm, hub) {
stream: swarm.stream,
offerConstraints: swarm.offerConstraints
})
peer.on('stream', function (stream) { peer.stream = stream; })

setup(swarm, peer, data.from)
swarm.remotes[data.from] = peer
Expand Down Expand Up @@ -163,7 +178,6 @@ function subscribe (swarm, hub) {
stream: swarm.stream,
offerConstraints: swarm.offerConstraints
})
peer.on('stream', function (stream) { peer.stream = stream; })

setup(swarm, peer, data.from)
}
Expand Down