Search code examples
rxjsreactive-programmingobserver-patternobserversreactive

How to unsubscribe all observers that watching observable made from 'fromEvent'?


Let's say I'm iterating the array to make the elements something like this:

var containerEl = document.createElement('div');
var list = [1, 2, 3, 4, 5];

list.map((data) => {
    var divEl = document.createElement('div');
    divEl.innerText = data;

    // Make observer for click
    divEl.onclick$ = fromEvent(divEl, 'click');

    containerEl.appendChild(divEl);
});

This should be result something like this:

<div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>

Important thing is that I added onclick$, which is observable:

divEl.onclick$ = fromEvent(divEl, 'click');

Now I can subscribe onclick something like this:

divEl.onclick$.subscribe(...);

However what if I redraw the all div elements that created while looping the list array?

To unsubscribe observation, I had to call unsubscribe, which included in returning value of subscription:

const a$ = divEl.onClick$.subscribe(...);

...

a$.unsubscribe();

That's quite uncomfortable, especially in modular / library development perspective.

Is there a way to unsubscribe all observers from divEl.onclick$ in this case?

Any advice will very appreciate it.


Solution

  • You can maybe use "takeUntil" operator like

    private unsubscriber$: Subject<boolean> = new Subject<boolean>();
    const a$ = divEl.onClick$.takeUntil(this.unsubscriber$).subscribe(...);
    
    ---
    // you want to unsubscribe 
    
    this.unsubscriber$.next(true);
    this.unsubscriber$.unsubscribe();
    

    Every observable on which you use takeUntil operator , will unsubscribe when you change the value inside the "unsubscriber$" observable