garethb garethb - 2 months ago 21
Javascript Question

Angular2 observables do I need to share

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.

Answer

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.

Comments