[Angular 2] Controlling Rx Subscriptions with Async Pipe and BehaviorSubjects
Each time you use the Async Pipe, you create a new subscription to the stream in the template. This can cause undesired behavior especially when network requests are involved. This lesson shows how to use a BehaviorSubject to observe the http stream so that only one request is made even though we still have two Async pipes in the template.
hero.component.html:
<div> <h2>{{description}}: {{(hero | async)?.name}}</h2> <div> <a [routerLink]="['/heros', prev()]">Previous</a> <a [routerLink]="['/heros', next()]">Next</a> </div> <div> <input type="text" #inpRef (keyup.enter)="saveHero(inpRef.value)"> </div> <br> <img src="{{(hero | async)?.image}}" alt=""> <div> <a [routerLink]="['/heros']">Back</a> </div> </div>
Here you can see, we use twice 'async' pipe, it means we subscribe the stream twice:
this.hero = this.route.params .map((p:any) => { this.editing = false; this.heroId = p.id; return p.id; }) .switchMap( id => this.starwarService.getPersonDetail(id));
In network tab, we can see it calls '1' api twice.
To solve this problem, we can use 'BehaviorSubject' :
this.hero = new BehaviorSubject({name: 'Loading...', image: ''}) this.route.params .map((p:any) => { this.editing = false; this.heroId = p.id; return p.id; }) .switchMap( id => this.starwarService.getPersonDetail(id)) .subscribe( this.hero);
This can solve problem, because we only have one subscription to the stream with HTTP get in it.
We do have two subscriptions to this contact here and here because a behavior subject is still an observable but it's not going to make two requests because now it's just observing what comes from the stream instead of basically invoking it twice. Because now we have one subscription to the stream with HTTP calling it being observed by something with two subscriptions on it.
See more: http://www.cnblogs.com/Answer1215/p/5784167.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-10-02 [Reactive Programming] RxJS dynamic behavior
2015-10-02 [Reactive Programming] Using an event stream of double clicks -- buffer()