假设我有一个可观察的队列类,如下所示:
function Queue(){
}
Queue.prototype.add = function(item){
return (an Observable);
}
Queue.prototype.read = function(){
return (an Observable);
}
每次将一个项目添加到队列中时,理想情况下,任何调用read的人都将获得下一个新项目。
所以我们有例如
const q = new Queue({some:data})
q.read().subscribe(); // stream of unique values
q.read().subscribe(); // stream of unique values
...
q.read().subscribe(); // stream of unique values
Queue实例和读取调用可能跨越单独的Node.js进程或在同一进程中,但无论如何,我想确保它们不从队列中读取重复值,我希望每个read方法都返回队列中唯一的新项目。
有没有办法用observables实现这个?我使用它们几乎是全新的。
这是一个天真且相当不正确的实现:
function Queue(){
this.items = [];
this.obsEnqueue = new Rx.Subject();
this._add = function(item){
this.items.push(item);
this.obsEnqueue.onNext(item);
}
}
Queue.prototype.add = function(item){
this._add(item);
// in real life this method will be async so we will return Observable
return (an Observable);
}
Queue.prototype.read = function(){
return this.obsEnqueue
.filter(item => {
return !item.isRead;
})
.map(item => {
item.isRead = true;
return item;
});
}
上面的代码肯定有问题,但也许你可以理解我想要做的事情。对于read方法有多个调用者,希望每个调用读取未读的项目。
我在read方法中将它们标记为已读,但我不确定该布尔标志是否正在通过原始数据源,以及其他读取方法是否会看到它。