Why rxjs debounceTime does not work on observables created using 'of' operator?

为君一笑 提交于 2020-06-12 10:39:22

问题


Using angular 7 and rxjs 6:

<input (input)="onChange($event.target.value)">

Why the following does not debounce?

onChange(val: string) {
  of(val)
    .pipe(        
      debounceTime(300)        
  ).subscribe(valx => {
    console.log(valx);
  });
}

But this does:

  searchTerm$: Subject<string> = new Subject();

  this.searchTerm$.pipe(      
    debounceTime(300),    
  ).subscribe(val => {
   console.log(val);
  });


onChange(val: string) {   
  this.searchTerm$.next(val);
}

回答1:


This isn't because of of(). In your first example every time you call onChange($event.target.value) you're creating a new chain with it's own debounceTime and it's own timer. So it never debounces anything because every input change has its own chain.

However, if you use Subject (like in your second example) and push all events through this.searchTerm$.next(val) then you have just one chain where each event is push at the top and then debounced as you expect.




回答2:


Consider your logic. You will create a finalised observer for each onChanges. It doesn't debounce because the observer is already finalized, and debounce is to prevent emitting one, in the off-chance that another one comes. So it needs at least two emitions to be justifiable (or more ), and that can't happen if the observer is created in the callback.



来源:https://stackoverflow.com/questions/54155003/why-rxjs-debouncetime-does-not-work-on-observables-created-using-of-operator

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