RxJS - take n last elements from an observable

前端 未结 2 843
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 13:20

I want to take 3 last elements from an observable. Let\'s say that my timeline looks like this:

--a---b-c---d---e---f-g-h-i------j->

where:

2条回答
  •  情话喂你
    2021-02-13 13:43

    You can use scan for this:

    from(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u'])
      .pipe(
        scan((acc, val) => {
          acc.push(val);
          return acc.slice(-3);
        }, []),
      )
      .subscribe(console.log);
    

    This will print:

    [ 'a' ]
    [ 'a', 'b' ]
    [ 'a', 'b', 'c' ]
    [ 'b', 'c', 'd' ]
    [ 'c', 'd', 'e' ]
    ...
    [ 's', 't', 'u' ]
    

    The bufferCount won't do what you want. It'll emit only when each buffer is exactly === 3 which means you won't get any emission until you post at least 3 messages.

    Jan 2019: Updated for RxJS 6

提交回复
热议问题