I am using Ionic3 with a rxjs/Observable
. I have the following function, and for some reason, even though the function is only called once, the 3rd line gets fired twice.
findChats(): Observable<any[]> {
return Observable.create((observer) => {
this.chatSubscription2 = this.firebaseDataService.findChats().subscribe(firebaseItems => {
this.localDataService.findChats().then((localItems: any[]) => {
let mergedItems: any[] = [];
if (localItems && localItems != null && firebaseItems && firebaseItems != null) {
for (let i: number = 0; i < localItems.length; i++) {
if (localItems[i] === null) {
localItems.splice(i, 1);
}
}
mergedItems = this.arrayUnique(firebaseItems.concat(localItems), true);
} else if (firebaseItems && firebaseItems != null) {
mergedItems = firebaseItems;
} else if (localItems && localItems != null) {
mergedItems = localItems;
}
mergedItems.sort((a, b) => {
return parseFloat(a.negativtimestamp) - parseFloat(b.negativtimestamp);
});
observer.next(mergedItems);
this.checkChats(firebaseItems, localItems);
});
});
});
}
Problem
This is causing a problem because this.chatSubscription2
is taking the value of the second subscription, and the first subscription gets lost, not allowing me to ever unsubscribe.
line 2 is executed once
line 3 is executed twice
Question
How do I create an Observable
with only one subscription?
Thanks
UPDATE
I change the code to the following using share()
, but the 3rd line still gets executed twice:
findChats(): Observable<any[]> {
return Observable.create((observer) => {
const obs = this.firebaseDataService.findChats().share();
this.chatSubscription2 = obs.subscribe(firebaseItems => {
....