Skip to content

🤓 RxJS operator that unsubscribe from observables on destroy

Notifications You must be signed in to change notification settings

gund/ngx-take-until-destroy

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

78 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

npm Build Status npm Awesome

🤓 Angular - Unsubscribe For Pros 💪

Declarative way to unsubscribe from observables when the component destroyed

Installation

npm install ngx-take-until-destroy --save

Usage

import { untilDestroyed } from 'ngx-take-until-destroy';

@Component({
  selector: 'app-inbox',
  templateUrl: './inbox.component.html',
})
export class InboxComponent implements OnInit, OnDestroy {
  ngOnInit() {
    interval(1000)
      .pipe(untilDestroyed(this))
      .subscribe(val => console.log(val));
  }

  // This method must be present, even if empty.
  ngOnDestroy() {
    // To protect you, we'll throw an error if it doesn't exist.
  }
}

Use with decorator

import { WithUntilDestroyed } from 'ngx-take-until-destroy';

@Component({...})
class MyComponent implements OnDestroy {
  @WithUntilDestroyed()
  stream$ = interval(1000); // You can safely subscribe to this everywhere

  // This method must be present, even if empty
  ngOnDestroy() {}
}

Use with any class

import { untilDestroyed } from 'ngx-take-until-destroy';

export class Widget {
  constructor() {
    interval(1000)
      .pipe(untilDestroyed(this, 'destroy'))
      .subscribe(console.log);
  }

  // The name needs to be the same as the decorator parameter
  destroy() {}
}

Live example

About

🤓 RxJS operator that unsubscribe from observables on destroy

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%