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

fix(pubsub): callback from unsubscribe after stream ends #772

Merged
merged 1 commit into from
May 18, 2018
Merged
Changes from all commits
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
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