themrdan
themrdan

Reputation: 117

Remove event listener inside promise

I am defining an event listener within a promise. The code works but I do not know how to remove the event listener. In the example, a promise is not used. However, I need to use the promise to wait for the audio to stop playing before playing the next audio. I am using react-native-sound-player.

This is my code:

 const playSound = async url => {
    try {
      const sound = new Promise((resolve, reject) => {
      SoundPlayer.addEventListener('FinishedPlaying', ({ success }) => {
      console.log('finished playing', success)
      resolve(success)      
      })}); 
    SoundPlayer.playSoundFile(url, 'mp3');
    await sound
    SoundPlayer.stop()
    } catch (e) {
      console.log(`cannot play the sound file`, e);
    }
  };

This is how the package example would remove the eventListener:

const playSound = url => {
    try {
      const sound = SoundPlayer.addEventListener('FinishedPlaying', ({ success }) => {
      console.log('finished playing', success)
      resolve(success)      
      })
    SoundPlayer.playSoundFile(url, 'mp3');
    
    SoundPlayer.stop()
    sound.remove()
    } catch (e) {
      console.log(`cannot play the sound file`, e);
    }
  };

But this would not work for my use case since I need to wait for the audio to finish playing before I can move onto the next audio. How can I remove the eventListener?

Upvotes: 0

Views: 1652

Answers (2)

Rodrigo Ehlers
Rodrigo Ehlers

Reputation: 1840

Your problem is that you're not using what is returned from .addEventListener. According to the docs, you need to use the returned SubscriptionObject to remove the subscription. Try the following

const playSound = async (url) => {
  try {
    const promise = new Promise((resolve, reject) => {
      const sound = SoundPlayer.addEventListener(
        "FinishedPlaying",
        ({ success }) => resolve(sound)
      );
    });

    SoundPlayer.playSoundFile(url, "mp3");
    const sound = await promise;
    SoundPlayer.stop();
    sound.remove();
  } catch (e) {
    console.log(`cannot play the sound file`, e);
  }
};

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65845

An event handler is set up by passing a reference to a function. It can then only be removed by passing the exact same reference. If you've set up the handler with an anonymous function, then by definition, there is no way to reference it later. Only named functions can be removed.

Exmaple:

function handler(){
  console.log("you invoked the handler");
}

document.getElementById("main").addEventListener("click", handler);

document.getElementById("remove").addEventListener("click", function(){
  document.getElementById("main").removeEventListener("click", handler);
});
<button id="main">Click Me</button>

<button id="remove">Remove Handler</button>

Upvotes: 1

Related Questions