How to subscribe to event emitter once? How to subscribe to event emitter once? angular angular

How to subscribe to event emitter once?


A call to subscribe returns an instance of Disposable, which has a method dispose.

Or if you are using RxJS 5, dispose has been renamed to unsubscribe (thanks @EricMartinez).

And from the RxJS docs:

...when we're no longer interested in receiving the data as it comes streaming in, we call dispose on our subscription.


Store the result of your call to subscribe and later dispose of the subscription within ngOnDestroy.

RxJS 5:

export class SomeComponent {  constructor (public service: Service) {    this.subscription = this.service.someEvent.subscribe((x) => {...});  }  ngOnDestroy () {      this.subscription.unsubscribe();  }}

RxJS <5:

export class SomeComponent {  constructor (public service: Service) {    this.subscription = this.service.someEvent.subscribe((x) => {...});  }  ngOnDestroy () {      this.subscription.dispose();  }}


You can do something like this:

import { OnDestroy } from '@angular/core';import { Subscription } from 'rxjs/Rx';export class SomeComponent implements OnDestroy {  private _subscription: Subscription;  constructor(public service: Service) {    this._subscription = this.service.someEvent.subscribe((x) => {      // Do something    });  }}ngOnDestroy(){  this._subscription.unsubscribe();}