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.