RxJS takeWhile but include the last value

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

    I came across the same problem, i needed the last element to be included so i chose to keep a reference to the subscription and unsubscribe within the onNext callback when the condition was met. Using your example code it would be:

    const subscription = Observable.of('red', 'blue', 'green', 'orange')
      .subscribe(color => {
        // Do something with the value here
        if (color === 'green') {
          subscription.unsubscribe()
        }
      }) 
    

    This worked for me because it also caused the observable source to stop emitting which is what i needed in my scenario. I realize that i'm not using takeWhile operator but the the main goal is achieved and without any workarounds or extra code. I'm not a fan of forcing things to work in a way that they were not designed to. The disadvantages of this are:

    • If there are any other observers subscribed, the source will keep emitting.
    • The onCompleted does not get called for some reason if the last observer unsubscribes, but i checked that the source in fact stops emitting.

提交回复
热议问题