chemerisuk / cordova-plugin-firebase-authentication

Cordova plugin for Firebase Authentication
MIT License
98 stars 60 forks source link

onAuthStateChanged() only invoked once #96

Closed Radecom closed 4 years ago

Radecom commented 4 years ago

Hello friend, first of all, congratulations on your excellent work making this plugin, with pleasure once I make it work in my application I will give you a donation. But now, I have an issue...

I am working with Ionic 5, and I have a main authentication service that contains an observable variable$ type that is bound to onAuthStateChanged().

When an element of my application subscribes this variable$ (onAuthStateChanged ()) works fine only once.

But if there is any change in the user session, like signOut() or signIn() the AuthStateChanged() is not invoked again automatically, I have to manually rerun a new subscription ... to read the current value authentication ...

IngAjVillalon commented 4 years ago

I also faced that problem ... but I solved it with the rxjs operator BehaviorSubject:

authStateSubject$ = new BehaviorSubject<firebase.User>(null);

Later I did 2 things, first I connected the authStateSubject$ to the onAuthStateChanged() like this:

this.firebaseAuthentication.onAuthStateChanged()
        .subscribe(auth => this.authStateSubject$.next( !!auth? auth: null ));

And when the user performed a sign in or sign out action, I send the result to the authStateSubject$ using its next() function.

authStateSubject$.netx(newUser || null);

Another tip makes sure that you make the subscriptions in the ngOnInit() because I mistakenly put a subscription in the constructor of the component and there I did not receive the new values until I changed it to ngOnInit().

With that, I was able to get everything working fine.

Radecom commented 4 years ago

That worked very well for me! Thank you very much @IngAjVillalon. How I promised in a moment I will send you the beer for you @chemerisuk.