简体   繁体   English

Rx.JS中的映射序列

[英]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: 例如:

  • AAA -> should print OK AAA - >应该打印好
  • AsssAqweA -> should print OK AsssAqweA - >应打印好
  • AAQAAQ -> shouldn't print anything AAQAAQ - >不应该打印任何东西
  • AAQAAA -> should print OK AAQAAA - >应打印好
  • AAAsssAAAsssAAA -> should print three times OK AAAsssAAAsssAAA - >应打印三次OK

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: 您应该能够使用filterscan操作符来执行您想要的操作:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM