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)
          ))
        )
    }
  • 相关阅读:
    当程序员的那些狗日日子
    程序员常犯的几个错误
    我没有帮你的义务,却有拒绝你的权力
    并发 并行 同步 异步 多线程的区别
    cookie的存取
    sqlserver 处理百万级以上的数据处理与优化
    为什么 jmeter 分布式测试,一定要设置 java.rmi.server.hostname
    详细解析 nginx uri 如何匹配 location 规则
    mysql innodb 从 ibd 文件恢复表数据
    mysql 从 frm 文件恢复 table 表结构的3种方法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12676794.html
Copyright © 2011-2022 走看看