1

I would appreciate some help with a problem involving subscriptions. I'm trying to prevent a callback function from being invoked by a delayed subscription in case a specific event happens, but I can't help managing to do it!

I've tried calling .unsubscribe(), when the event handler is triggered, but that didn't stop the callback from being executed.

Here's the definition of my subscription:

this.sub = Observable
    .of(true)
    .pipe(
         delay(2000)
    )
    .subscribe(() => {
        foo()
    });

And here's what I've tried:

this.elRef.nativeElement.onmouseover = () => {
    if (this.sub) {
      this.sub.unsubscribe();
    }
};

Thanks in advance

Jota Renan
  • 266
  • 2
  • 4
  • 11
  • 1
    This might give you some ideas: https://stackoverflow.com/questions/34728827/rxjs-if-with-observable-as-conditional – Brandon Taylor Jan 25 '19 at 19:34
  • The above code works for me, foo() is not executed after mouseover. – ABOS Jan 25 '19 at 19:42
  • 1
    Calling `.unsubscribe()` is enough to stop receiving new emissions. Are you sure this `this.sub.unsubscribe();` is called when `this.sub` exists? – martin Jan 25 '19 at 20:41

1 Answers1

1

Here is a solution using takeUntil and a Subject. Here is an article about this technique. This pattern is often used to automatically unsubscribe on ngOnDestroy.

import { Component, OnDestroy } from '@angular/core';
import { Observable, of, Subject } from 'rxjs';
import { delay, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnDestroy  {
    destroy$: Subject<boolean> = new Subject<boolean>();

    sub = of(true)
        .pipe(
            delay(2000),
            takeUntil(this.destroy$)
        )
        .subscribe(() => {
            this.foo();
        });

    onMouseOver(): void {
        this.destroy$.next(true);
    }

    ngOnDestroy(): void {
        this.destroy$.next(true);
        this.destroy$.unsubscribe();
    }
}

Hope that helps!

jo_va
  • 13,504
  • 3
  • 23
  • 47