Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2248
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

22条回答
  •  花落未央
    2020-11-21 05:13

    Angular 2 official documentation provides an explanation for when to unsubscribe and when it can be safely ignored. Have a look at this link:

    https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

    Look for the paragraph with the heading Parent and children communicate via a service and then the blue box:

    Notice that we capture the subscription and unsubscribe when the AstronautComponent is destroyed. This is a memory-leak guard step. There is no actual risk in this app because the lifetime of a AstronautComponent is the same as the lifetime of the app itself. That would not always be true in a more complex application.

    We do not add this guard to the MissionControlComponent because, as the parent, it controls the lifetime of the MissionService.

    I hope this helps you.

提交回复
热议问题