Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does startWith('') typescript code do?

I'm learning Angular 5 with Typescript. I'm trying to implement an angular material autocomplete and I've found the following code which is very obscur to me :

this.filteredStates = this.stateCtrl.valueChanges
  .pipe(
    startWith(''),
    map(state => state ? this.filterStates(state) : this.states.slice())
  );

The full code can be found here : https://stackblitz.com/angular/mdokmnyajmd?file=app%2Fautocomplete-overview-example.ts

I tend to think that when a changed occurs on stateCtrl, then it returns the filterStates(state) result if and only if a concrete element has been selected in autocomplete.

What I don't understand is the use of startWith('') ?! Why not simpling call subscribe on valueChanges ?

like image 670
Anthony Hocquet Avatar asked Jan 26 '18 16:01

Anthony Hocquet


People also ask

What is StartWith in angular?

startWith(... values: D[]): OperatorFunction<T, T | D> Returns an observable that, at the moment of subscription, will synchronously emit all values provided to this operator, then subscribe to the source and mirror all of its emissions to subscribers.

What does StartWith do in RXJS?

RxNet StartWith Rx.NET implements this operator as StartWith . It accepts an array of items which it prepends to the resulting Observable sequence in the order they appear in the array before it emits the items from the source Observable.


1 Answers

valueChanges will not emit any values initially (until state actually changes). When you need to calculate something from initial state you use startWith to make observable emit a value even though it wouldn't normally.

If you want to process initial value without startWith, you can create another stream

Observable.of(stateCtrl.value).pipe(
  map(state => state ? this.filterStates(state) : this.states.slice())
);

which will emit only one value. But it's easier to handle both cases at the same time, so startWith is a good way to do it...

like image 80
Sasxa Avatar answered Oct 24 '22 16:10

Sasxa