Tecayehuatl
Tecayehuatl

Reputation: 310

is there another way to auto subscribe /unsubscribe to an observable than async pipe?

I am wondering if there's another way to auto subscribe/unsubscribe from an observable? I have seen async pipe mostly in html template, but what about when I want to do something in my component class, talking about when you're working in an angular project for example.

Upvotes: 3

Views: 2108

Answers (3)

Fan Cheung
Fan Cheung

Reputation: 11345

You can probably create a base class to do so and extend it with your component class, then you don't have to repeat the ngDestory handling for every component that you created.

 export class BaseComponent implements OnDestroy {
    public _subscriptions: Subscription[] = [];

    addSubscription(...sub): Subscription | Subscription[] {
        this._subscriptions.concat(sub);
        return sub;
    }

    ngOnDestroy(): void {
        this._subscriptions.forEach(s =>
            s.unsubscribe()
        );
    }
}

example usuage

class MyComp extends BaseComponent{
    ngOnInit(){
        this.addSubscription(interval(1000).subscribe())
    }
}

Upvotes: 1

Tal Ohana
Tal Ohana

Reputation: 1138

I would recommend one of the following unsubscribe methods:

  1. async pipe
  2. Using takeUntil operator:
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
  private readonly componentDestroyed$ = new Subject();

  ngOnDestroy(): void { this.componentDestroyed$.next() }

  ngOnInit(): void {
    myObservable$.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => {
      // your code here...
    })
  }
}

  1. Using subsink to help you manage subscriptions
  2. Using decorator-based approach such as ngx-auto-unsubscribe for angular < 9 or until-destroy for angular >= 9

Upvotes: 4

Syntiara
Syntiara

Reputation: 303

You can make use of a behavior subject like this

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    export class ComponentA implements OnInit, OnDestroy {
     private componentUnload$ = new Subject<boolean>();

       constructor(
        public dataService: DataService,
      ) {}


        ngOnInit() {
        this.dataService.items$ // here, you are calling an observable
          .pipe(takeUntil(this.componentUnload$))
          .subscribe(items => {
            this.items = items;
          });
      }

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

Upvotes: 0

Related Questions