我如何一次只能激活X个可观察物?

时间:2018-09-08 07:17:11

标签: rxjs rxjs5 rxjs6

  

我正在使用RxJS v6,但答案也适用于RxJS v5。

我想这样做,所以如果我说8个值,那么一次只能处理4个。

我现在拥有的代码发送4个项目,然后等到所有4个完成,然后再发送下4个。我希望它在前4个中发送,然后作为一个可观察的完成,再来一个待处理。

from([1, 2, 3, 4, 5, 6, 7, 8])
.pipe(
    bufferCount(4),
    concatMap(values => (
        from(values)
        .pipe(
            mergeMap(value => (
                timer(1000) // Async stuff would happen here
                .pipe(
                    mapTo(value),
                )
            )),
        )
    )),
)
.subscribe(console.log)

1 个答案:

答案 0 :(得分:4)

您必须使用第二个参数mergeMap,该参数允许您指定所需的并发 级别

所以您的代码看起来像

from([1, 2, 3, 4, 5, 6, 7, 8])
.pipe(
    map(val => of(val)),
    mergeMap(val => val, 4),
)
.subscribe(console.log)

of([1, 2, 3, 4, 5, 6, 7, 8])
.pipe(
    mergeMap(val => val, 4),
)
.subscribe(console.log)

考虑concatMapmergeMap,并发级别设置为1。

阅读this SO post,以获取有关mergeMap的更多详细信息。

相关问题