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)
          ))
        )
    }
  • 相关阅读:
    [原]POJ1141 Brackets Sequence (dp动态规划,递归)
    [转]10分钟入门python
    [原]sdut2605 A^X mod P 山东省第四届ACM省赛(打表,快速幂模思想,哈希)
    [原]SQL_实验2.1.3 清华大学出版社
    [原]sdut2624 Contest Print Server (大水+大坑)山东省第四届ACM省赛
    [原]hdu2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活 (这个只是题目名字) (多重背包)
    快速幂运算
    山东省acm省赛 I Sequence(动态规划)
    [ACM] 携程预赛第一场 括号匹配 (动态规划)
    [ACM] poj 1141 Brackets Sequence (动态规划)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12676794.html
Copyright © 2011-2022 走看看