RxJS - take n last elements from an observable

心已入冬 提交于 2019-12-04 02:08:39

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

You can look at Observable#bufferCount function. One difference is that it wants at least 3 times to emit (first parameter, in this example).

const source = Rx.Observable.interval(1000);
const example = source.bufferCount(3,1)
const subscribe = example.subscribe(val => console.log(val));
<script src="https://unpkg.com/@reactivex/rxjs@5.4.3/dist/global/Rx.js"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!