Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unsubscribe from a Firebase list in Angular2?

I am connecting to a Firebase list using

tasks: FirebaseListObservable<ITask[]>;

constructor(private af: AngularFire) {
  this.tasks = this.af.database.list("/tasks");
}

And now I want to cancel that connection, when my users logout.

I already tried this.tasks.unsubscribe(), but looks like the method is undefined (I tried this because FirebaseListObservable is an observable).

I also tried this.tasks.off() as suggested in the documentation, but it is also undefined.

Finally, I tried this.tasks = null and that works, but I'm not sure if that is the correct implementation.

like image 207
Fernando Popoca Ortiz Avatar asked Feb 20 '17 03:02

Fernando Popoca Ortiz


1 Answers

this.tasks is an Observable not a Subscription which is why you cannot unsubscribe.

If you are manually subscribing then you can:

let observable = Rx.Observable.interval(1000);
let subscription = observable.subscribe(x => console.log(x));
subscription.unsubscribe();

If you are using the async pipe then Angular will automatically unsubscribe when the component is destroyed. Based on the source code, the observable will be unsubscribed if the value of the pipe changes to null, but this is not specified in the docs anywhere. I think a better option would be to explicitly destroy the components where you use the async pipe.

like image 195
shusson Avatar answered Oct 24 '22 07:10

shusson