【问题标题】:Why isn't there a endWith operator in Rx?为什么 Rx 中没有 endWith 运算符?
【发布时间】:2017-03-22 12:00:25
【问题描述】:

拥有像.startWith 这样方便的方法,让他的对立面.endWith 是有意义的,这使得observable 在完成时产生一个值。

我想出了这个解决方案,但还有什么更好的吗?这东西有点难读。

source.concat(Rx.Observable.just(lastValue))

【问题讨论】:

  • 你做对了。没有endWith,因为cocnat 正是它已经做到的。请注意,也有类似用途的defaultIfEmpty
  • @martin 实际上,对于我的具体情况,defaultIfEmpty 就足够了。没注意到那个接线员,谢谢!

标签: rxjs observable


【解决方案1】:

在 RxJS6 中有(老实说不知道是什么时候添加的)

文档

https://rxjs-dev.firebaseapp.com/api/operators/endWith

来源: https://github.com/ReactiveX/rxjs/blob/df0ea7c78767c07a6ed839608af5a7bb4cefbde5/src/internal/operators/endWith.ts

另外,defaultIfEmpty() 仅在 observable CLOSES 没有发出值的情况下发出一个值。这是一个微妙的,但不是那么微妙的区别。在有限的情况下,它可能与endWith() 具有相同的效果。

endWith() 示例:

const source = of(1, 2, 3, 4, 5);
const example = source.pipe(
                            takeWhile(val => val != 4), 
                            endWith(4));

发射:

[1, 2, 3, 4]

我还注意到https://learnrxjs.io 网站越来越过时,目前不显示此运算符。

我为什么需要它?

我一直在寻找能够发出 false 直到条件变为 true 的能力,但永远不要回到 false。有点类似于去抖动,但不完全一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 2011-09-14
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2018-09-23
    相关资源
    最近更新 更多