在可观察的RXJS中管理内部状态
我是RXJ的新手,想知道内部状态。
我们的用例是返回初始状态(具有IDS的项目列表)和可观察到将突变(已删除ID)的可观察到的承诺。然后,更新的项目列表是一个持久状态,应用于构建结果。
我可以使用一个全局变量将一些东西侵入,但正如预期的那样,它的行为很奇怪:
import { combineLatest, from } from "rxjs";
import { startWith } from "rxjs/operators";
...
const initialObservable = from(initialPromise);
const mutationObservableWithStart = mutationObservable.pipe(startWith(null));
const globalDeletedIds: string[] = [];
return combineLatest([initialObservable, mutationObservableWithStart]).pipe(
map(([items, mutation]) => {
if (mutation && mutation.deleted) {
globalDeletedIds.push(mutation.id);
}
const currentItems = items.filter(doesNotIncludeIds(globalDeletedIds));
return buildResult(currentItems);
})
);
我的问题是:如何在可观察到的内部状态正确管理内部状态?
I'm new to RxJS and wondering about internal state.
Our use case is a promise that returns an initial state (a list of items with ids) and an observable that streams mutations (deleted ids) to that state. The updated list of items is then a persistent state and should be used in building the result.
I can hack something together using a global variable but as expected it behaves weirdly:
import { combineLatest, from } from "rxjs";
import { startWith } from "rxjs/operators";
...
const initialObservable = from(initialPromise);
const mutationObservableWithStart = mutationObservable.pipe(startWith(null));
const globalDeletedIds: string[] = [];
return combineLatest([initialObservable, mutationObservableWithStart]).pipe(
map(([items, mutation]) => {
if (mutation && mutation.deleted) {
globalDeletedIds.push(mutation.id);
}
const currentItems = items.filter(doesNotIncludeIds(globalDeletedIds));
return buildResult(currentItems);
})
);
My question is: how to correctly manage internal state in an observable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解问题是正确的,我会这样继续(Inline评论尝试解释逻辑),
您可以看一下此stackblitz 示例。
If I understand the problem right, I would proceed like this (inline comments try to explain the logic)
You can take a look at this stackblitz for an example.