Reputation: 5485
Can you guys tell me what is wrong here.
RxJS
I was expecting the value will print only one time,but it is printing mulitple times
function Search(sel) {
let observable = Rx.Observable.fromEvent(document.getElementById('iCard'), 'input');
observable
.debounceTime(1000)
.distinctUntilChanged()
.subscribe({
next: this.callGlobalSearch
});
}
function callGlobalSearch(e){
console.log('VALUE : ', e.target.value); // NOT SURE, WHY THE VALUE IS PRINTED MULTIPLE TIMES
}
Upvotes: 1
Views: 3188
Reputation: 2621
Changed your code in fiddle check here. You don't need to subscribe to input
event on every keyup
. And distinctUntilChanged
was getting event object which is different always. So it can't do anything. Before that event should be mapped to text, then it can be compared in distinctUntilChanged
.
Rx.Observable.fromEvent(document.getElementById('iCard'), 'input')
.debounceTime(1000)
.map(e => e.target.value)
.distinctUntilChanged()
.subscribe({
next: callGlobalSearch
});
function callGlobalSearch(text) {
console.log('VALUE : ', text);
}
Upvotes: 4
Reputation: 17762
Any time you keyup
you run the function Search(sel)
.
Any time you run the function Search(sel)
you create an Observable and you subscribe to it.
So after n keyup
events you end up having n active subscriptions to n different source Observables, and therefore you see n repetitions of the line logged on the console.
If change the html code such as
<body onload="Search(this)">
Global Search
<input id="iCard" type='text' />
</body>body>
you should get the right behavior.
Change the name of the function Search
to something more aligned to the real stuff performed, e.g. createInputObs
, according to your style.
Upvotes: 2