问题描述
我想从 observable 中取出 3 个最后的元素.假设我的时间线如下所示:
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->
其中:a、b、c、d、e、f、g、h、i、j 是发射值
每当发出新值时,我想立即获取它,因此它看起来像这样:
Whenever a new value is emitted I want to get it immediately, so it can look 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
我认为这非常有用.想象一下,建立一个聊天室,您希望显示 10 条最后的消息.每当收到新消息时,您都希望更新您的视图.
I think that this is super useful. Imagine building a chat where you want to display 10 last messages. Whenever a new message comes you want to update your view.
我的尝试:演示
推荐答案
您可以使用 scan
来解决这个问题:
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);
这将打印:
[ 'a' ]
[ 'a', 'b' ]
[ 'a', 'b', 'c' ]
[ 'b', 'c', 'd' ]
[ 'c', 'd', 'e' ]
...
[ 's', 't', 'u' ]
bufferCount
不会做你想做的事.仅当每个缓冲区恰好是 === 3
时它才会发出,这意味着您在发布至少 3 条消息之前不会得到任何发射.
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.
2019 年 1 月:针对 RxJS 6 更新
Jan 2019: Updated for RxJS 6
这篇关于RxJS - 从 observable 中取出最后 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!