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)
          ))
        )
    }
  • 相关阅读:
    【转】Flask安装
    【转】Mac OS X 中 Zsh 下 PATH 环境变量的正确设置
    【转】谁说Vim不是IDE?(二)
    【转】谁说Vim不是IDE?(三)
    【转】谁说Vim不是IDE?(一)
    【转】终极 Shell
    【转】开始使用Mac OS X——写给Mac新人
    【转】如何实现一个malloc
    《神经网络和深度学习》系列文章十六:反向传播算法代码
    Vue.js之生命周期
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12676794.html
Copyright © 2011-2022 走看看