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)
          ))
        )
    }
  • 相关阅读:
    Luogu 4206 [NOI2005]聪聪与可可
    【Luogu】P3708Koishi的数字游戏(数论)
    【Luogu】P1850换教室(期望DP)
    【Luogu】P1231教辅的组成(拆点+Dinic+当前弧优化)
    【Luogu】P3865ST表模板(ST表)
    【Luogu】P3376网络最大流模板(Dinic)
    【Luogu】P1005矩阵取数游戏(高精度+DP)
    【Luogu】P2324骑士精神(IDA*)
    【Luogu】P3052摩天大楼里的奶牛(遗传算法乱搞)
    洛森地图半成品
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12676794.html
Copyright © 2011-2022 走看看