unsubscribe:Angular 项目中常见场景以及是否需要 unsubscribe

本文探讨了Angular项目中不同场景下使用observablesubscribe时是否需要unsubcribe,重点讲解了finite和infiniteobservable的区别,以及HttpClient、BehaviorSubject、FormControl和DOM事件监听等情况下unsubcribe的必要性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文由庄汇晔同学编写~

在 Angular 项目中,经常会使用到 observable subscribe,但是 subscribe 读取了数据之后,真的就是万事大吉了吗?这个问题的答案或许是,或许不是。有些 observable 需要 unsubscribe,而有些并不用。在接下来的文章里,我会介绍:

  • observable 的种类:何种 observable 需要 unsubscribe,以及没有 unsubscribe 会造成什么样的问题。
  • 在 angular 项目中,可能会遇到的observable 的场景,以及他们是否需要 unsubscribe,为什么需要/不需要?
  • unsubscribe 的方法。

一、observable 的种类:何种 observable 需要 unsubscribe,以及没有unsubscribe 会造成什么样的问题。

从 observable 能否结束(complete)的角度来看,observable 分为两类:finite observable(有限事件流)和 infinite observable(无限事件流)。区分他们的方法很简单:即 finite observable 只能 emit 一个值(或是一个错误),随即结束。而 infinite observable 会 emit 多个值,而不会结束。

finite Observable 的例子有:http client request,infinite Observable 的例子有:DOM eventListener。如果不取消订阅,将会出现内存泄漏,执行意料之外回调函数的问题。所以,一定需要 unsubscribe 的是 infinite observable(无限事件流),而 finite observable(有限事件流)一般不需要 unsubscribe。

二、在 angular 项目中,可能会遇到的 subscribe 的场景,他们需要 unsubscribe 吗?为什么需要/不需要?

1、Http Client 请求(this.httpClient.get(…).subscribe)

fetchFromBackend() {
   
  let subscription$ = this.http.get(`http://example.com`).subscribe(...)
}

是否需要 unsubscribe:视情况而定。

原因:http client 为有限事件流,当 Observable complete 后,angular 会自动关闭 Observable。由于 unsubscribe http client request 并不意味着取消请求,而是取消了返回数据后的回调函数,所以需要根据场合来取消 subscription。如果在回调函数中,如果有会造成内存泄漏的代码,则严格意义上来说,应该需要 unsubscribe

更多详情请移步阅读:https://medium.com/angular-in-depth/why-you-have-to-unsubscribe-from-observable-92502d5639d0

2、Component 之间传递信息使用的 Behavior subject

// in service file
@Injectable({
   
  providedIn: 'any',
})
export class MyComponentService {
   
  public dataSource = new BehaviorSubject < any > (null);
  ....
}

// in component data boardcaster
this.myComponentService.dataSource.next(...)

// in component data subscriber
this.myComponentService.dataSource.subscribe(...)

是否需要 unsubscribe:需要。

原因:这种为无限事件流,无法预期它的回调函数会造成什么样的问题,所以需要 unsubscribe

3、Form control,响应式表单的变化监听(例如:this.form.valueChanges.subscribe)

initForm() {
   
  this.form = new FormGroup({
    ...});
  this.valueChanges = this.form.valueChanges.subscribe(...);
}

是否需要 unsubscribe:需要。

原因:这种为无限事件流,虽然 component unmount 后,form 也不存在,但是这样会造成内存泄漏,导致性能下降等问题。

4、Dom 中的 fromEvent 事件监听(例如:Observable.fromEvent(this.element.nativeElement, ‘click’).subscribe)

@ViewChild('myElement', {
    static: false })
myElement: ElementRef;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值