zoukankan      html  css  js  c++  java
  • Rxjs debounce 操作符在 SAP Spartacus 函数节流中的一个实际使用例子

    在 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' }
    
  • 相关阅读:
    开发中的一些总结。。。
    Directory Listing Denied错误
    webservice的一些使用心得。。
    vs2005 sp1 补丁后,不能初始化
    谈C/C++指针精髓
    CString 的函数
    javaScript 中 call 函数的用法说明 & 继承
    条款12: 尽量使用初始化而不要在构造函数里赋值(effectiveC++)
    js日期时间函数(经典+完善+实用)
    学习之路一 记录学习中的手记
  • 原文地址:https://www.cnblogs.com/sap-jerry/p/14671269.html
Copyright © 2011-2022 走看看