【问题标题】:RXJS observable evaluate multiple time?RXJS 可观察多次评估?
【发布时间】:2016-02-16 17:02:37
【问题描述】:

我在 Angular2 应用程序中使用 NGRX 和 RxJS。当使用尝试保存记录更新时,我会生成一个操作“更新”,我想调用 API 来更新数据库。

问题是“.filter (action => action.type==UPDATE)”之后的所有内容都被调用了 4 次。

我不明白为什么。我尝试了很多东西并更改了代码,但问题仍然存在......

我的代码:

private actions$ : BehaviorSubject<Action> = new BehaviorSubject<Action>({type: null, payload: null});

.../.... 

// catch employee selection
let update = this.actions$                                  
            .filter ( action => action.type==UPDATE )
             // **** following are executed 4 times ****
            .do( () => this._store.dispatch({type: REDUCER_UPDATING }) )
            .mergeMap ( action =>this._APIService.updateEmployee(action.payload) );  //  


// merge all stream and dispatch action
let all = Observable.merge (update, load, selectItem);
all.subscribe ((action:Action) => this._store.dispatch (action));

实时查看问题:

https://plnkr.co/edit/zq4AsKJYILfrgItDNbHo?p=preview

在主面板中选择一名员工。在详细信息面板中,单击保存按钮。您将在控制台中看到 API 被调用了 4 次:

REDUCER - {"type":"SELECTING_ITEM","payload":1}
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE          <====1
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE          <====2
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE          <====3
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE          <====4
REDUCER - {"type":"UPDATED"}

感谢您的帮助!!

【问题讨论】:

  • 代码示例中的小修正。我不使用 do 运算符,而是使用 mergeMap :// catch employee selection let update = this.actions$ .filter ( action =&gt; action.type==UPDATE ) .do( () =&gt; this._store.dispatch({type: REDUCER_UPDATING }) ) .mergeMap ( action =&gt;this._APIService.updateEmployee(action.payload) );

标签: javascript angular rxjs ngrx


【解决方案1】:

我将update 部分替换为:

// catch employee selection
let update = this.actions$                                  
            .filter ( action => action.type==UPDATE )
             // **** following are executed 4 times ****
            .do( () => this._store.dispatch({type: REDUCER_UPDATING }) )
            .mergeMap ( action =>this._APIService.updateEmployee(action.payload) )
            .share();  //  

这导致日志中只出现一个更新。

您观察到更新重复的原因是因为每次您订阅更新流时,可观察链都会“重新启动”。这就是在 RxJS 中所谓的冷可观察对象。解决方案很简单,只需在要在多个订阅者之间共享的 observable 末尾添加 share

有关热与冷的更多详细信息,请参阅official documentation。您也可以查看illustrated data and subscription flows

【讨论】:

  • 我在您的代码示例中看不到任何变化;)。我尝试添加 .share () 来更新表达式并修复此问题。我会阅读您的参考资料以了解何时需要!谢谢您的帮助 !真的!
  • 哦,是的,我从错误的 plunkr 粘贴了代码。对此感到抱歉。现在更新了代码。关于多个订阅,其中一个是您在此处提供的all.subscribe ((action:Action) =&gt; this._store.dispatch (action)); 还有其他几个地方您有东西(从记忆中,我现在无法查看代码),例如 all.map 放入其他稍后订阅的流中上。所以all被订阅了多次,导致更新订阅了多次。如果您没有看到相关的订阅,则说明是 Angular2 在幕后操作订阅。
  • 好的,没错。我现在看到我有多个订阅!感谢您的回复:我输了很多次才弄清楚出了什么问题,但现在,我可以进步了! :) 再次发送!
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 2021-08-22
  • 2020-02-01
  • 2019-10-18
  • 2016-05-17
  • 2017-06-11
  • 2016-10-29
  • 1970-01-01
相关资源
最近更新 更多