gpt4 book ai didi

javascript - 如何在不完成添加序列的情况下从 rxjs 创建数组

转载 作者:行者123 更新时间:2023-11-29 19:14:09 25 4
gpt4 key购买 nike

我正在尝试找出一种 rxjs 方法来执行以下操作:

您有两个可观察对象,一个是 onAddObs 和一个 onRemoveObs。假设 onAddObs.next() 触发了几次,添加了“A”、“B”、“C”。然后我想得到 ["A", "B", "C"]。

.toArray 需要完成 observable...但可能还会有更多。

这是第一部分。第二部分可能很明显......我希望 onRemoveObs 然后从最终结果数组中删除。

我没有 plunkr 因为我做不到任何东西......提前致谢!

更新

根据 user3743222 的建议,我检查了 .scan,它完成了工作!如果其他人遇到了这个问题,我已经包含了一个 angular2 服务,它显示了一个很好的方法来做到这一点。诀窍是使用 .scan 而不是添加/删除的流,而是要添加/删除的函数流,这样您就可以从扫描中调用它们并传递状态。

@Injectable() 
export class MyService {

public items: Observable<any>;
private operationStream: Subject<any>;

constructor() {

this.operationStream = Subject.create();

this.items = this.operationStream
// This may look strange, but if you don't start with a function, scan will not run....so we seed it with an operation that does nothing.
.startWith(items => items)
// For every operation that comes down the line, invoke it and pass it the state, and get the new state.
.scan((state, operation:Function) => operation(state), [])
.publishReplay(1).refCount();

this.items.subscribe(x => {
console.log('ITEMS CHANGED TO:', x);
})
}

public add(itemToAdd) {
// create a function which takes state as param, returns new state with itemToAdd appended
let fn = items => items.concat(itemToAdd);
this.operationStream.next(fn);
}

public remove(itemToRemove) {
// create a function which takes state as param, returns new array with itemToRemove filtered out
let fn = items => items.filter(item => item !== itemToRemove);
this.operationStream.next(fn);
}

}

最佳答案

您可以在此处引用 SO 问题:How to manage state without using Subject or imperative manipulation in a simple RxJS example? .它处理与您的问题相同的问题,即两个流对一个对象执行操作。

其中一项技术是使用 scan 运算符和对保存在 scan 中的状态进行操作的操作流,但无论如何都要看看链接,这是非常形成的。这应该允许您编写一些代码。如果该代码无法按您希望的方式工作,您可以返回并在此处使用您的示例代码再次提问。

关于javascript - 如何在不完成添加序列的情况下从 rxjs 创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com