RxJS takeWhile but include the last value

后端 未结 6 936
情书的邮戳
情书的邮戳 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 05:11

    UPDATE March 2019, rsjx version 6.4.0: takeWhile finally have an optional inclusive parameter that allows to keep the first element that breaks the condition. So now the solution would be simply to pass true as the second argument of takeWhile:

    import { takeWhile } from 'rxjs/operators';
    import { from } from 'rxjs';
    
    const cutOff = 4.5
    const example = from([2, 3, 4, 5, 6])
    .pipe(takeWhile(v => v < cutOff, true ))
    const subscribe = example.subscribe(val =>
      console.log('inclusive:', val)
    );
    

    outputs:

    inclusive: 2
    inclusive: 3
    inclusive: 4
    inclusive: 5
    

    Live here:

    https://stackblitz.com/edit/typescript-m7zjkr?embed=1&file=index.ts

    Notice that 5 is the first element that breaks the condition. Notice that endWith is not really a solution when you have dynamical conditions like v < cutOff and you don't know what will be your last element.

    Thanks @martin for pointing out the existence of this pull request.

提交回复
热议问题