Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1466字,纯文字阅读大概需要3分钟。
内容图文
![Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子](/upload/InfoBanner/zyjiaocheng/1012/d12fa8004c774efd9c00127a072a2dc0.jpg)
在 window-ref.ts 的实现里,定义了一个每隔 300 毫秒,通过 fromEvent 发射一个 resize event 的Observable:
/**
* Returns an observable for the window resize event and emits an event
* every 300ms in case of resizing. An event is simulated initially.
*
* If there's no window object available (i.e. in SSR), a null value is emitted.
*/
get resize$(): Observable<any> {
if (!this.nativeWindow) {
return of(null);
} else {
return fromEvent(this.nativeWindow, 'resize').pipe(
debounceTime(300),
startWith({ target: this.nativeWindow }),
distinctUntilChanged()
);
}
}
加上 distingctUntilChanged 操作符后,能过滤掉完全一致的 resize event. 下面的例子,展示了如何使用 distingctUntilChanged,将数字序列里重复的数字过滤掉。distingctUntilChanged 默认会将当前元素和前一元素做比较。
import { of } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(
distinctUntilChanged(),
)
.subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
下列例子展示了如何将自定义的比较逻辑,通过箭头函数作为参数,传入 distinctUntilChanged 里。
import { of } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
interface Person {
age: number,
name: string
}
of<Person>(
{ age: 4, name: 'Foo'},
{ age: 7, name: 'Bar'},
{ age: 5, name: 'Foo'},
{ age: 6, name: 'Foo'},
).pipe(
distinctUntilChanged((p: Person, q: Person) => p.name === q.name),
)
.subscribe(x => console.log(x));
// displays:
// { age: 4, name: 'Foo' }
// { age: 7, name: 'Bar' }
// { age: 5, name: 'Foo' }
内容总结
以上是互联网集市为您收集整理的Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子全部内容,希望文章能够帮你解决Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。