Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子

举报
Jerry Wang 发表于 2022/05/18 12:13:27 2022/05/18
【摘要】 在 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 e...

在 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' }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。