@ngrx 选择器并行发射两次

Gia*_*Voß 5 rxjs ngrx

我有一个非常简单的选择器

\n\n
export const isLoading = createSelector(\n  state => state.$loading\n);\n
Run Code Online (Sandbox Code Playgroud)\n\n

和两个操作StartLayoutNavigationActionEndLayoutNavigationAction只需$loading相应地设置标志。\n我调用这些函数一次,我的操作就会被记录:

\n\n
ACTION \xe2\x80\x93 [Layout] Start navigation StartLayoutNavigationAction\xc2\xa0{layout: "login", type: "[Layout] Start navigation"}\nACTION \xe2\x80\x93 [Layout] End navigation EndLayoutNavigationAction\xc2\xa0{type: "[Layout] End navigation"}\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,人们会假设选择器将在调用第一个操作时发出一次,在调用第二个操作时发出一次。中间没有任何动作。

\n\n

但:

\n\n

选择器似乎并行发出两次。我管道如下:

\n\n
layoutLoading$: Observable<boolean> = this.store.pipe(\n  select(isLoading),\n  distinctUntilChanged((x, y) => {\n    console.log("Comparison:", x, y);\n    return x === y;\n  }),\n  tap(value => console.log("New val:", value))\n);\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是输出:

\n\n
ACTION \xe2\x80\x93 [Layout] Start navigation StartLayoutNavigationAction\xc2\xa0{layout: "login", type: "[Layout] Start navigation"}\nComparison:  false true\nNew val: true\nComparison: false true\nNew val: true\nACTION \xe2\x80\x93 [Layout] End navigation EndLayoutNavigationAction\xc2\xa0{type: "[Layout] End navigation"}\nComparison: true false\nNew val: false\nComparison: true false\nNew val: false\n
Run Code Online (Sandbox Code Playgroud)\n\n

我是不是搞错了什么?这是预期的行为吗?

\n

Bug*_*ggy 2

根据评论

\n\n
\n

您确定layoutLoading$只有一个订阅吗?例如,您有多个异步管道、多个组件实例。- @巴吉

\n
\n\n
const source$ = of(1).pipe(\n  tap(value => console.log("New val:", value))\n);\n\nsource$.subscribe();\nsource$.subscribe();\n// 1\n// 1\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

好吧,你是对的,我有两个异步订阅。我不知道\n这适用于每个订阅。因此,当我想要对不同的更改做出反应(除了异步管道之外)时,我将需要第二个可观察管道,对吧?- @Giacomo Vo\xc3\x9f

\n
\n\n

是的,如果我理解正确的话:

\n\n
source$\n  .pipe(distinctUntilChanged(fn))\n  .subscribe(/* do something */)\n
Run Code Online (Sandbox Code Playgroud)\n