为什么RXJS角度行为主题会产生多个值 [英] Why RXJS angular behaviorSubject emit mutiple values

查看:59
本文介绍了为什么RXJS角度行为主题会产生多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处输入图片描述我使用 BehaviorSubject 在我的应用程序组件之间共享数据,由于从 BehaviorSubject 多次发射相同的值,所以我遇到了性能问题.例如,我调用http从后端获取团队对象并将其存储在behaviorSubject中,许多组件都订阅了此 BehaviorSubject .每个组件都从订阅中获取值,并对值进行一系列操作.问题的实质是,该值会发出多次,并且每个组件都会多次执行所有序列.我的猜测是 BehaviorSubject 发出的值是订阅者数量.我在Google中找不到对我来说很奇怪的任何东西,我想念的是什么?

enter image description hereI use BehaviorSubject to share data between my app components, I have a performance issue due to mutiple emission of same value from BehaviorSubject. For instance, I call http to get team Object from backend and store it in a behaviorSubject, many components subscribe to this BehaviorSubject. Each component gets the value from subscription and does a sequence of manipulations on the value. The essence of the problem is that the value is emitted many times and each component does all sequence a few times. My guess is the the BehaviorSubject emits the value as number of subscribers. I couldn't find anything in Google which is very strange to me, what am I missing ?

与部署相比,团队在本地产生价值的次数有所不同.您可以看到打印的"refref返回值"是来自http的实际响应.

The number of times the team emit value is different in local compared to deployment. You can see the the printing of "refetch returned value" it is the actual response from http.

推荐答案

您可以通过仅接受不同于最后一个值的值来部分解决此问题,从而连续跳过几次对同一值的求值.

You can partially fix it by only accepting values different than the last one, thus skipping evaluating the same value a few times in a row.

此外,如果您查询的数据可以与之前的查询相同,则最好还是添加以下内容:

Also, if the data you query can be the same as the previous query, it may be a good idea to add this anyway:

import { distinctUntilChanged } from 'rxjs/operators';

this.myService.myObservable
    .pipe(distinctUntilChanged())
    .subscribe(value => {
        console.log(value);
    })

这篇关于为什么RXJS角度行为主题会产生多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆