sathishvj
sathishvj

Reputation: 1464

Cancel observable after first time - Angular2, TypeScript, rxjs/Observable

I’m doing a check for existing login at start of app which I want only once. How do we cancel that subscription after the first time? I tried take(1) but that doesn't seem to work.

this.auth.getUserData().take(1).subscribe(data => { // the take(1) doesn't work
  console.log('Firebase responded with success.');
  this.rootPage = TabsPage;
 }, err => {
  console.log('Firebase responded with error.', err);
  this.rootPage = LoginEmailPage;
 }
);

Upvotes: 2

Views: 7113

Answers (1)

Ben Dadsetan
Ben Dadsetan

Reputation: 1565

Have you tried first() instead of take(1)

Depending on your imports at the module level, you may want to add an import for the first operator

import 'rxjs/add/operator/first'

While this does not actually cancel the subscription, it completes the observation which is which I believe is what was meant.

EDIT: adding the explicit way of cancelling the subscription as originally requested by the OP

The result of .subscribe(...) will return a handler to the subscription. You can use that handle to explicitly cancel the subscription and the code would look like this:

let subscription = this.auth.getUserData().take(1).subscribe(data => { // the take(1) doesn't work
  console.log('Firebase responded with success.');
  this.rootPage = TabsPage;
  subscription.unsubscribe();
 }, err => {
  console.log('Firebase responded with error.', err);
  this.rootPage = LoginEmailPage;
 }
);

While it feels wrong to explicitly cancel the subscription in this case, a common pattern is to create the subscription within ngOnInit() or based on post init events, and cancel pending subscriptions within the ngOnDestroy().

Upvotes: 3

Related Questions