[英]Map sequence in Rx.JS
I would like to map correct sequence using Rx.js. 我想使用Rx.js映射正确的序列。 A simplest example will be using keyboard.
最简单的例子是使用键盘。 I attach Rx.js to keyboard events and waiting for three A no matter what will be between them, except Q. When sequence is matched I would like to print OK on console.
我将Rx.js附加到键盘事件并等待三个A,无论它们之间是什么,除了Q.当序列匹配时,我想在控制台上打印OK。 For example:
例如:
Should I use filter function and keep state inside it? 我应该使用过滤功能并保持状态吗? Or there is an esier way to do that.
或者有一种更为有效的方法。
You should be able to use the filter
and scan
operators to do what you want: 您应该能够使用
filter
和scan
操作符来执行您想要的操作:
Rx.Observable.from("AsssAqweAbAAQAAA") // Only A and Q characters are important: .filter(char => (char === "A") || (char === "Q")) // Accumulate the A characters until there are three // or until a Q is received: .scan((acc, char) => { if ((char === "Q") || (acc.length === 3)) { acc = []; } if (char === "A") { acc.push(char); } return acc; }, []) // Filter the accumulated characters until there // are three: .filter(acc => acc.length === 3) .mapTo("OK") .subscribe(value => console.log(value));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
You could try it with a bufferCount
- though I'm not certain if your given examples are simplified and in reality a little more complex, but maybe this helps: 您可以尝试使用
bufferCount
- 虽然我不确定您的示例是否已经简化,实际上有点复杂,但这可能会有所帮助:
const source$ = Rx.Observable.from("aaqassaaassaaa"); source$.bufferCount(3, 1) // .do(console.log) // uncomment to see the processed data .filter(data => data.join("") === "aaa") // your detection-logic .mapTo("Ok") .subscribe(console.log);
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.