Angularfire: Proposal: Using BehaviorSubject<T> instead of Observable

Created on 13 Oct 2017  路  3Comments  路  Source: angular/angularfire

I would like to propose to have an Option to return BehaviorSubject instead of Observable.
The idea is if multiple Components need to fetch the same data, then it would be obvious to wrap the query into a Service. But when using observables, only the first component would fetch the data from the example shown below. When we would route to the second component the observable would not return any data on subscription. So the actual solution to this issue is to create another observable and to fetch the same data again. But by means of I/O and code reusing is this not a very good approach.

Actual:

@Injectable()
export class DataService {
  private shirtCollection: AngularFirestoreCollection<Shirt>;
  shirts: Observable<ShirtId[]>;
  constructor(private readonly afs: AngularFirestore) {
    this.shirtCollection = afs.collection<Shirt>('shirts');
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });
  }

  getShirts(): Observable<ShirtId[]>{
     return this.shirts:
  }
}

As we see in the example above, if the "shirts" Observable could be a type of BehaviorSubject, then all components using Service to subscribe on the shirtCollection would always get the last state of the collection.

Most helpful comment

This should accomplish the same thing, I think

this.shirts = this.shirtCollection.snapshotChanges()
  .map(...)
  .shareReplay(1);

All 3 comments

This should accomplish the same thing, I think

this.shirts = this.shirtCollection.snapshotChanges()
  .map(...)
  .shareReplay(1);

Your solution to this problem is really awesome. I have tested it and it works!
Thx a lot.

Thanks for the good answer @willshowell
Going to close, we decided against any sort of caching in the module itself, instead allowing the developer to implement what they need. We wouldn't want to blow things up on large collections, etc.

Was this page helpful?
0 / 5 - 0 ratings