zoukankan      html  css  js  c++  java
  • [RxJS] Build an Event Combo Observable with RxJS (takeWhile, takeUntil, take, skip)

    After another pat on the back from our manager, we get a notification that a new task has been assigned to us: “While most users find it useful, some have asked if they can disable the spinner. Add a feature that turns off the spinner functionality once a certain combination of keys has been pressed within a time period”. So in this lesson, we will look at building an observable factory, that can be initialized with a certain list of key codes, and will fire whenever that key combo gets pressed quickly, within a 5 second window. We will be introducing the fromEvent, concat and takeWhile operators.

    Idea is the interval will be stop only when user pressed the 'a', 's', 'd', 'f' key in order.

    Between each keypressed, should wait no longer than 3 seconds.

    import { Observable, interval, timer, fromEvent } from 'rxjs'; 
    import { tap, map, skip, filter, switchMap, takeUntil, takeWhile, take} from 'rxjs/operators';
    
    const anyKeyPressed = fromEvent(document, 'keypress')
      .pipe(
        map((event: KeyboardEvent) => event.key),
        tap((key) => console.log(`key ${key} is pressed`))
      )
    
    function keyPressed (key) {
      return anyKeyPressed.pipe(
        filter(pressedKey => pressedKey === key)
      )
    }
    
    function keyCombo(keyCombo) {
      return keyPressed(keyCombo[0])
        .pipe(
          switchMap(() => anyKeyPressed.pipe(
            takeUntil(
              timer(3000).pipe(
                tap(() => console.log('stoped, no futher key detected'))
              )
            ),
            // check from 's' 'd', f'
            takeWhile((keyPressed, index) => {
              console.log(keyPressed, index + 1)
              return keyCombo[index + 1] === keyPressed
            }),
            // skip 's' &' d'
            skip(keyCombo.length - 2),
            // complete it when last 'f' emit
            take(1)
          ))
        )
    }
    
    const comboTriggered = keyCombo(["a", "s", "d", "f"])
    
    interval(1000)
      .pipe(takeUntil(comboTriggered))
      .subscribe(
        x => {
        console.log(x)
      },
      err => console.error('not ok'),
      () => console.log('completed')
      )

    There is an issue with our combo implementation: given that we're switchMapping to a new inner combo each time the user presses the combo initiation key (the letter "a" in our example), if the initiation key is found anywhere in the middle of the combo, it will just cancel out any on-going inner combos.

    To fix it, we'll look at the differences between switchMap and exhaustMap and why exhaustMap is a much better choice for our scenario: switchMap disposes of any previous inner observables when it gets a new notification from the source, while exhaustMap waits for the inner observable to finish, before considering any new notifications from the source.

    function keyCombo(keyCombo) {
      return keyPressed(keyCombo[0])
        .pipe(
          exhaustMap(() => anyKeyPressed.pipe(
            takeUntil(
              timer(3000).pipe(
                tap(() => console.log('stoped, no futher key detected'))
              )
            ),
            // check from 's' 'd', f'
            takeWhile((keyPressed, index) => {
              console.log(keyPressed, index + 1)
              return keyCombo[index + 1] === keyPressed
            }),
            // skip 's' &' d'
            skip(keyCombo.length - 2),
            // complete it when last 'f' emit
            take(1)
          ))
        )
    }
  • 相关阅读:
    tetrahedron (公式)
    Subway (树中心 + 树hash)
    包装类的Null值
    基本数据类型的范围边界
    基本数据类型的装箱和拆箱()优先使用基本数据类型
    第三章-python基础 笔记
    第二章-Python起步
    第一章-欢迎来到python世界
    第八章-连接与多张表的操作
    php错误和异常的处理方式
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12676794.html
Copyright © 2011-2022 走看看