thecanteen
thecanteen

Reputation: 784

What does unsubscribe() do in this firebase auth sample?

On this page https://firebase.google.com/docs/auth/web/google-signin#expandable-2 there is a code sample where a function calls itself (see text in bold below) -- I'm confused what this means, can anybody please shed some light -- why does unsubscribe call itself?

  console.log('Google Auth Response', googleUser);
  // We need to register an Observer on Firebase Auth to make sure auth is initialized.
  var unsubscribe = firebase.auth().onAuthStateChanged((firebaseUser) => {
    unsubscribe();

Upvotes: 0

Views: 265

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

Calling onAuthStateChanged() "adds an observer/listener for changes to the user's sign-in state" AND returns an unsubscribe function that can be called to cancel the listener.

So the goal of the following pattern

var unsubscribe = firebase.auth().onAuthStateChanged((firebaseUser) => {
    unsubscribe();

    // ...
});

is to listen only once for changes to the user's sign-in state. The first time the listener is triggered it calls the unsubscribe function, so it doesn't listen anymore.

As explained in the comment in the code you refer to, they use this pattern in order to make sure auth is initialized.


Note that one could have very well done:

var foo = firebase.auth().onAuthStateChanged((firebaseUser) => {
    foo();

    // ...
});

Upvotes: 3

Related Questions