0

My ionic 5 (Angular) project uses Google firebase database.

This is an example code I used to read data from firebase database. I just want to read the data only once. As valueChanges() is a observable, I guess I have to unsubscribe the subscription every time when use it.

constructor(db: AngularFireDatabase) {
    this.tempsub = db.list('items').valueChanges().subscribe(data=>{...});
    this.tempsub.unsubscribe()
  }

Do I have to unsubscribe it in my use case? Is there a better solution to read the data from firebase database only once?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
lei lei
  • 1,753
  • 4
  • 19
  • 44

2 Answers2

1

You can use the take operator to configure the desired number of emissions.
Using take(1) will emit the first value, then complete and unsubscribe.

db.list('items').valueChanges()
  .pipe(take(1))
  .subscribe(...);
Reqven
  • 1,688
  • 1
  • 8
  • 13
0

You can also use forEach() which returns a promise that will either resolve or reject when the Observable completes or errors.

You cannot unsubscribe from forEach(), but you don't need to unsubscribe in this case since take(1) takes the first value from the source, then completes.

db.list('items').valueChanges()
  .pipe(take(1))
  .forEach(items => do something with items);
Wilhelm Mauch
  • 23
  • 1
  • 6