问题
I have a form input for a search. When a user enters something in the search input I need to call 2 separate api's. This is what I'm trying to achieve:
myInput: new FormControl();
listOne: Observable<string[]>;
listTwo: Observable<string[]>;
ngOnInit(){
this.listOne = this.myInput.valueChanges
.debounceTime(500)
.distinctUntilChanged()
.switchMap(myInput => this._service.getListOne(myInput));
this.listTwo = this.myInput.valueChanges
.debounceTime(500)
.distinctUntilChanged()
.switchMap(myInput => this._service.getListTwo(myInput));
}
So my question is, how do I subscribe to valueChanges and call 2 different api's to fill 2 different arrays? With the code above, it works great on the initial search, but when I change the search text, only getListTwo is called.
回答1:
Whenever a source has several subscribers, and you want those subscribers to read the same value from that source (in other words you want to multicast the source values to several subscribers), you should share.
Here that means : sharedSource = this.myInput.valueChanges.debounceTime(500).distinctUntilChanged().share(), so for example :
myInput: new FormControl();
listOne: Observable<string[]>;
listTwo: Observable<string[]>;
ngOnInit(){
this.listOne = sharedSource
.switchMap(myInput => this._service.getListOne(myInput));
this.listTwo = sharedSource
.switchMap(myInput => this._service.getListTwo(myInput));
}
You can have a look at the detailed explanation here of multicast vs. cold streams.
回答2:
ngOnInit(){
input$ = this.myInput.valueChanges.debounceTime(500)
.distinctUntilChanged()
.share();
this.listOne = input$.switchMap(myInput => this._service.getListOne(myInput));
this.listTwo = input$.switchMap(myInput => this._service.getListTwo(myInput));
//store subscriptions
this.subs$.push(input$,this.listOne,this.listTwo);
}
Remember to unsubscribe to avoid memory leaks:
ngOnDestroy(){
this.subs$.forEach(s => s.unsubscribe());
}
来源:https://stackoverflow.com/questions/39359427/angular2-observables-do-i-need-to-share