RxJS takeWhile but include the last value

后端 未结 6 928
情书的邮戳
情书的邮戳 2020-12-06 04:16

I have a RxJS5 pipeline looks like this

Rx.Observable.from([2, 3, 4, 5, 6])
  .takeWhile((v) => { v !== 4 })

I want to keep the subscrip

6条回答
  •  心在旅途
    2020-12-06 04:50

    Since RxJS 6.4.0 this is now possible with takeWhile(predicate, true).

    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:

    1. using concatMap():

      of('red', 'blue', 'green', 'orange').pipe(
        concatMap(color => {
          if (color === 'green') {
            return of(color, null);
          }
          return of(color);
        }),
        takeWhile(color => color),
      )
      
    2. Using multicast():

      of('red', 'blue', 'green', 'orange').pipe(
        multicast(
          () => new ReplaySubject(1),
          subject => subject.pipe(
            takeWhile((c) => c !== 'green'),
            concat(subject.take(1),
          )
        ),
      )
      

    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

    This operator has been also discussed in this RxJS 5 issue: https://github.com/ReactiveX/rxjs/issues/2420

    Jan 2019: Updated for RxJS 6

提交回复
热议问题