javascript - 如何将一个流按顺序拆分成多个流
问题描述
使用 RxJS 6,
我有一个任意数据流:
[in] -> a, b, c, d, e, f, g, h, i, ....
我想以交替顺序将其拆分为固定数量的 N 个流(在本例中为 3 个输出流):
[out] -> stream1 -> a, d, g
-> stream2 -> b, e, h
-> stream3 -> c, f, i
或更简单地说:
a => stream1
b => stream2
c => stream3
d => stream1
e => stream2
f => stream3
g => stream1
h => stream2
i => stream3
有谁知道我该怎么做?
解决方案
您可以N
使用以下方法在每次迭代时迭代并将流分成两部分partition
:
import { from, merge } from 'rxjs';
import { partition, map } from 'rxjs/operators';
const source = from(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']);
function split(source, n) {
const streams = [];
let toSplit = source;
for (let k = n; k > 0; --k) {
const [stream, rest] = toSplit.pipe(
partition((_, i) => i % k === 0)
);
streams.push(stream);
toSplit = rest;
}
return streams;
}
const obs = split(source, 3);
const subscribe = merge(
obs[0].pipe(map(val => `1: ${val}`)),
obs[1].pipe(map(val => `2: ${val}`)),
obs[2].pipe(map(val => `3: ${val}`)),
).subscribe(val => console.log(val));
推荐阅读
- python - 解决 Python 模块错误以启用 Web Scraping 脚本?
- rust - 为什么在使用 `print!` 时,Rust 似乎会乱序执行语句/表达式?
- javascript - 如何在反应中制作阅读更多按钮?
- javascript - React Native 元素未按预期呈现
- reactjs - reactJs App js - 将传入数据作为道具传递
- ubuntu - 如何找到依赖于已弃用库的 PHP 模块?
- java - GC 如何将不可访问对象标记为已不可访问
- android - AdMob Native Advanced 宽度和空白可点击
- python - PonyORM/Postgres 多租户选项
- php - 如何在laravel的产品表字段中插入具有3位唯一ID的类别名称