Skip to content
This repository has been archived by the owner on Mar 10, 2020. It is now read-only.

Commit

Permalink
fix: callback from unsub after stream ends
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Alan Shaw <[email protected]>
  • Loading branch information
alanshaw committed May 17, 2018
1 parent faa51b4 commit 51a80f2
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/pubsub.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,29 @@ module.exports = (arg) => {

// Drop the request once we are actually done
if (ps.listenerCount(topic) === 0) {
subscriptions[topic].abort()
if (!callback) {
return new Promise((resolve, reject) => {
// When the response stream has ended, resolve the promise
eos(subscriptions[topic].res, (err) => {
// FIXME: Artificial timeout needed to ensure unsubscribed
setTimeout(() => {
if (err) return reject(err)
resolve()
})
})
subscriptions[topic].req.abort()
subscriptions[topic] = null
})
}

// When the response stream has ended, call the callback
eos(subscriptions[topic].res, (err) => {
// FIXME: Artificial timeout needed to ensure unsubscribed
setTimeout(() => callback(err))
})
subscriptions[topic].req.abort()
subscriptions[topic] = null
return
}

if (!callback) {
Expand Down Expand Up @@ -154,13 +175,16 @@ module.exports = (arg) => {

// Start the request and transform the response
// stream to Pubsub messages stream
subscriptions[topic] = send.andTransform(request, PubsubMessageStream.from, (err, stream) => {
subscriptions[topic] = {}
subscriptions[topic].req = send.andTransform(request, PubsubMessageStream.from, (err, stream) => {
if (err) {
subscriptions[topic] = null
ps.removeListener(topic, handler)
return callback(err)
}

subscriptions[topic].res = stream

stream.on('data', (msg) => {
ps.emit(topic, msg)
})
Expand Down

0 comments on commit 51a80f2

Please sign in to comment.