RxJS - take the last elements from observable

I want to take the last 3 elements from observable. Say my timeline looks like this:

--a---bc---d---e---fghi------j->

where: a, b, c, d, e, f, g, h, i, j are emitted values

Whenever a new value is issued, I want to get it immediately so that it looks like this:

 [a] [a, b] [a, b, c] [b, c, d] [c, d, e] [d, e, f] [e, f, g] [f, g, h] ... and so on 

I think this is super helpful. Imagine you are creating a chat where you want to display the 10 most recent posts. When a new message arrives, you want to update your presentation.

My attempt: demo

+10
javascript rxjs reactive
source share
2 answers

You can use scan to do 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' ] 

bufferCount will not do what you want. It will emit only when each buffer is exactly === 3 which means that you will not receive any radiation until you send at least 3 messages.

+18
source share

You can see Observed # bufferCount . One difference is that it wants to emit at least 3 times (the 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> 
+4
source share

All Articles