Reputation: 8935
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
subscribe
?Any advise appreciated.
Upvotes: 4
Views: 9002
Reputation: 275847
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
Docs on take
: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/take.md
Upvotes: 3