4

I have the following Observable:

dataService.ts

findMessages(chatItem: any): Observable<any[]> {
    return Observable.create((observer) => {
        this.firebaseDataService.findMessages(chatItem).subscribe((firebaseItems: any[]) => {
              // do something
                observer.next(somedata);
        });
    });
}

which calls this function:

firebaseDataService.ts

findMessages(chatItem: any): Observable<any[]> { // populates the firelist
    return this.af.database.list('/message/', {
        query: {
            orderByChild: 'negativtimestamp'
        }
    }).map(items => {
        const filtered = items.filter(
            item => ((item.memberId1 === chatItem.memberId1 && item.memberId2 === chatItem.memberId2)
                || (item.memberId1 === chatItem.memberId2 && item.memberId2 === chatItem.memberId1))
        );
        return filtered;
    });
}

The dataService.findMessages(chatItem) function is only ever called once.

This observes the firebase list. So if any items on the list change, this Observable is fired.

Problem

If the function is accessed, or one item is added to the list, the Observer is fired as expected, but the // do something line is called multiple times. I would only expect it to be called once.

Question

  • Is there a way to enforce that it's only called once?
  • Or once it's called for the first time, to break out of the
    subscribe?
  • Or, is my code completely wrong?

Any advise appreciated.

Richard
  • 8,193
  • 28
  • 107
  • 228

1 Answers1

3

but the // do something line is called multiple times

It is called in the callback passed to this.firebaseDataService.findMessages(chatItem).subscribe. The subscribe function will fire whenever there is a new item. If you only want to take one item you can use the take operator

More

Docs on take : https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/take.md

Community
  • 1
  • 1
basarat
  • 261,912
  • 58
  • 460
  • 511