-1

I figured the mongodb change stream extends the EventEmitter class, so I tried removing events I installed by using the removeListener function. After calling removeListener on the change stream it still fired on change. May be I'm just using the wrong function reference when removing, but I can not see how.

I found out removeAllListeners does remove the attached listener. But I need to be in control what listener to remove.

const change_listener = (change) => {
    console.log(change_stream.listenerCount("change"))
    change_stream.removeListener("change", change_listener)
    console.log(change_stream.listenerCount("change"))
}
change_stream.on("change", change => change_listener(change))

should output 1 0

but it outputs 1 1

and the listener goes on listening.

Using .once instead of .on only helps half the way. I would still need removeListener because I need to be able to cancel the listener early.

lasse
  • 95
  • 8
  • 1
    could you use `.once` instead of `.on`? – Manuel Spigolon Mar 26 '19 at 16:11
  • I need to be able to cancel the listener in case. Thanks for the hint though! Good to know this is also possible – lasse Mar 26 '19 at 19:50
  • if you look at the docs of `EventEmitter` right below `removeAllListeners` there is another function where you can specify the event as well as the function. – RisingSun Mar 26 '19 at 19:59
  • Well, if you mean removeListener, thats the one Im describing here that is not working as I expect it to. – lasse Mar 26 '19 at 20:21

1 Answers1

1

The problem is due to the function you are removing.

This should work:

const change_listener = (change) => {
    console.log(change_stream.listenerCount("change"))
    change_stream.removeListener("change", change_listener)
    console.log(change_stream.listenerCount("change"))
}
change_stream.on("change", change_listener)

Note that change => change_listener(change) is a function and it is different from change_listener

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
  • This is of course exactly the problem and has nothing to do with mongo change streams... Thanks a lot for your help and for looking closely! – lasse Mar 26 '19 at 23:02