您有一个非常常见的情况需要处理,即相关操作取决于某些控制状态的事件(即您有一个基本状态机)。基本上,如果您考虑这两个控制状态:SIMPLE_KEY、COMBO,以及这两个事件:keyup 和keyupTimer,那么:
- 处于
SIMPLE_KEY 状态
- 如果按下的键是
o,则切换到COMBO状态
- 如果不是
o,那么我们保持相同的状态,并将密钥传递给下游
- 如果是定时器事件,那么我们传递一个空值被下游过滤掉
- 处于
COMBO 状态
- 我们累积按下的键
- 如果定时器事件,那么我们恢复到
SIMPLE_KEY状态
因此,要将您的事件映射到一个动作,您需要知道您所处的控制状态。运算符scan 允许您根据累积的状态决定如何处理事件。
可能是这样的 (https://jsfiddle.net/cbhmxaas/):
function getKeyFromEvent(ev) {return ev.key}
function isKeyPressedIsO(ev) {return getKeyFromEvent(ev) === 'o'}
const KEY = 'key';
const TIMER = 'timer';
const COMBO = 'combo';
const SIMPLE_KEY = 'whatever';
const timeSpanInMs = 1000;
const keyup$ = Rx.Observable.fromEvent(document, 'keyup')
.map(ev => ({event: KEY, data: getKeyFromEvent(ev)}));
const keyupTimer$ = keyup$.flatMapLatest(eventStruct =>
Rx.Observable.of(eventStruct)
// .tap(console.warn.bind(console, 'timer event'))
.delay(timeSpanInMs)
.map(() => ({event : TIMER, data: null}))
);
Rx.Observable.merge(keyup$, keyupTimer$)
// .tap(console.warn.bind(console))
.scan((acc, eventStruct) => {
if (acc.control === SIMPLE_KEY) {
if (eventStruct.event === KEY) {
if (eventStruct.data === `o`) {
return {control: COMBO, keyOrKeys : []}
}
else {
return {control: SIMPLE_KEY, keyOrKeys : eventStruct.data}
}
}
else {
// TIMER event
return {control: SIMPLE_KEY, keyOrKeys : null}
}
}
else {
// we only have two states, so it is COMBO state here
if (eventStruct.event === KEY) {
return {control: COMBO, keyOrKeys : acc.keyOrKeys.concat([eventStruct.data])}
}
else {
// this is a TIMER event, we only have two events
return {control: SIMPLE_KEY, keyOrKeys : acc.keyOrKeys}
}
}
}, {control: SIMPLE_KEY, keyOrKeys : null})
// .tap(console.warn.bind(console))
.filter(state => state.keyOrKeys) // TIMER event in SIMPLE_KEY state
.map (({control, keyOrKeys}) => {
// Here you associate your action
// if keyOrKeys is an array, then you have a combo
// else you have a single key
console.log('key(s) pressed', keyOrKeys)
return keyOrKeys
})
.subscribe (console.log.bind(console))