Remove() function in Observer remove other observers

Removing an Observer modifies the array with all Observers from an Observable.

The array is only a reference, and any modifications during the loop execution will affect the next iteration on the same loop. Adds on top of it that the observers are executed in sequence, not in parallel.

Get the following example:

const arr = [0 , 1, 2, 3];

for (const val of arr) {
  console.log(val);
  arr.shift(); // Removes the first position of the array
}

The result is:

0
2

This is due of the usage of a pointer to get the next position on the array and modifying the array during the loop.
In your example, if you had a third observer, the third one would be executed.

Thus, at this moment you cannot remove the handlers inside of the handler itself, which can be considered a bug, or just “working as intended”.

Nevertheless, if you want to execute only once, you can use Observable.addOnce() instead of Observable.add(). If that is not the cause, you have to find another way to remove the handlers outside the loop of execution.

2 Likes