1

Do we ever need to unsubscribe from an Observable? When is the time we need to use unsubscribe?

I read an angularfire2 article talking about using firebase.auth to check user's login status. In the end of code, he unsubscribes from auth.subscribe. https://javebratt.com/angularfire2-email-auth/ (please see app.component.ts).

I was really confused, since I thought the Observable will "unsubscribe" itself after completed or on error.

Do we need to unsubscribe from observable that completes/errors-out? and Do you need to unsubscribe from Angular 2 http calls to prevent memory leak?

Community
  • 1
  • 1
George Huang
  • 2,504
  • 5
  • 25
  • 47

3 Answers3

2

You're correct about unsubscribing on complete or error notification.

I think the key is the comment in getAuth() method in auth.ts:

Please observe the actual authState asynchronously by subscribing to the auth service: af.auth.subscribe()

So you should subscribe with af.auth.subscribe(...) to be notified when the actual authState changes. This means that it doesn't complete (similarly to Observable.fromEvent(...)) and you have to unsubscribe manually.

martin
  • 93,354
  • 25
  • 191
  • 226
1

Well, not only do complete and error events unsubscribe from the Observable, but that's actually the proper way to unsubscribe.

The advantages of completing vs unsubscribing, as listed in this post, are:

  • usually less code
  • better factored / designed code; your completion rules are in one place; where a subscription begins and where it ends are in one place
  • you take advantage of the complete event to write any "completion / clean up" code (there's no unsubscribe event)
zafeiris.m
  • 4,339
  • 5
  • 28
  • 41
0

I also got an answer from the author:

Jorge Vergara

You don't need to (do unsubscribe()). I do it because I only want the observable to send people to those pages on app startup, if I'm going to log my user in or make some changes in auth I don't want that observer firing up and redirecting my users somewhere.

George Huang
  • 2,504
  • 5
  • 25
  • 47