Observable create is called twice

你离开我真会死。 提交于 2019-12-23 16:43:44

问题


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 => {
                     ....

回答1:


As other users have suggested, while findChats is only called once, it would seem that the observable it returns is subscribed to multiple times. create returns a cold observable which will cause all the internal logic to be executed for each subscription. You can whack a share on the end of the whole thing (i.e. outside / after the create call) to test this, but I would suggest the solution would actually be simpler if you did not use create at all, and rather just mapped / flatMapped / switchMapped your original stream into your desired stream (to avoid manual subscription management).



来源:https://stackoverflow.com/questions/44883886/observable-create-is-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!