Reputation: 24324
I have this code in Angular
this.provider.getUids()
.then(uidObservable => this.uidsSubscription$ = uidObservable.subscribe((uids: string[]) => {
console.log('res', uids); // array of uids
const uidsSet = new Set(uids); // deletes duplicates
uidsSet.forEach(uid => {
this.userObservables.push(this.otherProvider.getSharedUserData(uid)); // this is the code I need to change
});
}))
When I trigger the observale to emit a new value. this.userObservables.push will have duplicate values.
Suppose I have only one uid: AAAAA then this.userObservables contains only observable to AAAAA Now, When I trigger the observable to emit a new value BBBBB this.userObservables will contain observables to AAAAA AAAAA BBBBB
Is there a way to prevent this sort of behavior I want to have an array of observables that emit like AAAAA BBBBB
Upvotes: 0
Views: 118
Reputation: 24324
I found a solution although not the best in my point of view. I reset the array of observables at the beginning of the subscribe method.
this.provider.getUids()
.then(uidObservable => this.uidsSubscription$ = uidObservable.subscribe((uids: string[]) => {
console.log('res', uids); // array of uids
const uidsSet = new Set(uids); // deletes duplicates
this.userObservables = [];
uidsSet.forEach(uid => {
this.userObservables.push(this._ShareListProvider.getSharedUserData(uid)); // this is the code I need to change
});
}))
Upvotes: 0
Reputation: 20063
You can do it like this:
this.uidsSubscription$ = Observable.fromPromise(this.provider.getUids())
.flatMap(obs$ => obs$)
.map(uids => new Set(uids))
.map(uids => uids.map(uid => this.otherProvider.getSharedUserData(uid)))
.subscribe(observables => this.userObservables = observables);
However, provider.getUids
returning a Promise<Observable<>>
sounds really weird and should probably be redesigned.
Also note that it's unusual to suffix a subscription with $
. The typical convention is to suffix observables that way, not subscriptions.
And, lastly, it also strikes me as odd that this observable only assigns an array of observables to some array. You'd typically want to continue the chain here so you subscribe to them in whatever fashion you need. Overall, the design of this code looks strange, but without more information this is just a XY problem.
Upvotes: 2