RxJS takeWhile but include the last value

后端 未结 6 929
情书的邮戳
情书的邮戳 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:57

    In my case, I was unable to predict what the final value would be. I also just wanted a solution involving common, easy operators, and I wanted something I could reuse, so I couldn't rely on the values being truthy. The only thing I could think of was defining my own operator like this:

    import { pipe, from } from 'rxjs';
    import { switchMap, takeWhile, filter, map } from 'rxjs/operators';
    
    export function doWhile(shouldContinue: (a: T) => boolean) {
      return pipe(
        switchMap((data: T) => from([
          { data, continue: true },
          { data, continue: shouldContinue(data), exclude: true }
        ])),
        takeWhile(message => message.continue),
        filter(message => !message.exclude),
        map(message => message.data)
      );
    }
    

    It's a little weird, but it works for me and I can import it and use it.

提交回复
热议问题