Quantcast
Channel: User Chris - Stack Overflow
Viewing all articles
Browse latest Browse all 39

Firestore listener subscription triggers random number of times

$
0
0

I have a Firestore listener that seems to trigger a random number of times. On the first page load, it might trigger 5 times, refreshing the page and it fires 13 times.

@Injectable({  providedIn: 'root',})export class AuthService {  user$: BehaviorSubject<SavedUser | undefined> = new BehaviorSubject<SavedUser | undefined>(undefined);  constructor(private angularFireAuth: AngularFireAuth, private firestore: AngularFirestore, private router: Router) {    this.onAuthStateChanged();  }  onAuthStateChanged() {    let counter = 0;    this.angularFireAuth.authState.subscribe(user => {      if (user) {        this.firestore          .collection('user')          .doc<User>(user.uid)          .valueChanges()          .subscribe(userRecord => {            counter++            console.log(counter); // Testing            user.getIdToken(true);            this.user$.next(userRecord);          });      }    });  }}

The output of the console log:

auth.service.ts:35 1auth.service.ts:35 2auth.service.ts:35 3auth.service.ts:35 4auth.service.ts:35 5auth.service.ts:35 6auth.service.ts:35 7auth.service.ts:35 8auth.service.ts:35 9auth.service.ts:35 10auth.service.ts:35 11

All I'm looking to do here is refresh the user's token when the document it's backed by changes.

I know the this.angularFireAuth.onAuthStateChanged(user => {...} is only triggered once, and no changes are happening to the document.

I've tried unsubscribing from the Firestore subscription via onDestroy however that made no difference.

As a "fix" I thought I would be able to read the first value and stop processing via

this.firestore  .collection('user')  .doc<User>(user.uid)  .valueChanges()  .pipe(first())  .subscribe(userRecord => {...});

Which did work at first sight, however that stops the .valueChanges() from triggering when the document is later changed.

Any tips?


Viewing all articles
Browse latest Browse all 39

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>