ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-04-13 12:33:23  阅读:206  来源: 互联网

标签:distinctUntilChanged Foo name debounce age Rxjs SAP event resize


在 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' }

标签:distinctUntilChanged,Foo,name,debounce,age,Rxjs,SAP,event,resize
来源: https://blog.csdn.net/i042416/article/details/115661000

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有