The observed creation is named twice

I am using Ionic3 with rxjs/Observable

. I have the following function, and for some reason, although the function is only called once, the 3rd line is being run 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 causes a problem because it this.chatSubscription2

takes on the value of the second subscription and the first subscription is lost rather than letting me unsubscribe.

line 2 is executed once
line 3 is executed twice

      

Question

How to create Observable

with only one subscription?

thank

UPDATE

I change the code to the following using share()

but the 3rd line is still executed twice:

findChats(): Observable<any[]> {
    return Observable.create((observer) => {
        const obs = this.firebaseDataService.findChats().share();
        this.chatSubscription2 = obs.subscribe(firebaseItems => {
                     ....

      

+2


source to share


1 answer


Like other users, while findChats is only called once, it seems that the observable it comes back is subscribed multiple times. create

returns a cold observable that will execute all internal logic for each subscription. You can hit share

at the end of the whole object (i.e. Outside / after the call create

) to test this, but I would suggest that the solution would be simpler if you didn't use at all create

and rather just mapped / flatMapped / switchMapped to your original stream to your desired stream (to avoid manual subscription management).



+3


source







All Articles