[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)
      ))
    )
}
复制代码

 

posted @   Zhentiw  阅读(379)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-04-10 [Tailwind] Style Elements on hover and focus with Tailwind’s State Variants
2018-04-10 [Tailwind] Apply mobile-first Responsive Classes in Tailwind
2018-04-10 [Tailwind] Create Custom Utility Classes in Tailwind
2018-04-10 [Tailwind] Get started with Tailwindcss
2017-04-10 [tmux] Copy and paste text from a tmux session
2017-04-10 [tmux] Customize tmux with tmux.conf
2017-04-10 [tmux] Zoom and resize to view a particular pane within tmux
点击右上角即可分享
微信分享提示