RxJS takeWhile 但包括最后一个值 [英] RxJS takeWhile but include the last value
问题描述
我有一个像这样的 RxJS5 管道
I have a RxJS5 pipeline looks like this
Rx.Observable.from([2, 3, 4, 5, 6])
.takeWhile((v) => { v !== 4 })
我想保留订阅直到看到 4,但我希望最后一个元素 4 也包含在结果中.所以上面的例子应该是
I want to keep the subscription until I see 4, but I want to last element 4 also to be included in the result. So the example above should be
2, 3, 4
但是,根据官方文档, takeWhile
运算符不包含.这意味着当它遇到与我们给出的谓词不匹配的元素时,它会立即完成流,而没有最后一个元素.结果,上面的代码实际上会输出
However, according to official document, takeWhile
operator is not inclusive. Which means when it encounters the element which doesn't match predicate we gave, it completes the stream immediately without the last element. As a result, the above code will actually output
2, 3
所以我的问题是,在实现 takeWhile
的同时还能用 RxJS 发出最后一个元素的最简单方法是什么?
So my question is, what's the easiest way I can achieve takeWhile
but also emit the last element with RxJS?
推荐答案
从 RxJS 6.4.0 开始,现在可以使用 takeWhile(predicate, true)
.
Since RxJS 6.4.0 this is now possible with takeWhile(predicate, true)
.
已经有一个开放的 PR 向 takeWhile
添加一个可选的 inclusive
参数:https://github.com/ReactiveX/rxjs/pull/4115
There's already an opened PR that adds an optional inclusive
parameter to takeWhile
: https://github.com/ReactiveX/rxjs/pull/4115
至少有两种可能的解决方法:
There're at least two possible workarounds:
使用
concatMap()
:
of('red', 'blue', 'green', 'orange').pipe(
concatMap(color => {
if (color === 'green') {
return of(color, null);
}
return of(color);
}),
takeWhile(color => color),
)
使用multicast()
:
of('red', 'blue', 'green', 'orange').pipe(
multicast(
() => new ReplaySubject(1),
subject => subject.pipe(
takeWhile((c) => c !== 'green'),
concat(subject.take(1),
)
),
)
我也一直在使用这个运算符,所以我把它变成了我自己的一组额外的 RxJS 5 运算符:https://github.com/martinsik/rxjs-extra#takewhileinclusive
I've been using this operator as well so I made it to my own set of additional RxJS 5 operators: https://github.com/martinsik/rxjs-extra#takewhileinclusive
这个操作符也在这个 RxJS 5 问题中讨论过:https://github.com/ReactiveX/rxjs/issues/2420
This operator has been also discussed in this RxJS 5 issue: https://github.com/ReactiveX/rxjs/issues/2420
2019 年 1 月:针对 RxJS 6 更新
Jan 2019: Updated for RxJS 6
这篇关于RxJS takeWhile 但包括最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!