
مين بيعمل unsubscribe لما الـ component يتشال؟ الـ subscriptions اللي بتسرّب memory
- كاتب موثّق
- Angular 22
محتويات المقال
الفكرة الغلط الشائعة
async pipe بيعمل unsubscribe لما الـ component بتاعته تتشال، وtoSignal() نفس الكلام، والـ effects كمان. وأغلب الـ subscriptions بتاعة HttpClient بتخلص لوحدها لأن الـ Observable بيعمل complete بعد الـ response، فالكود اللي بيعمل subscribe على HTTP calls ومابيعملش unsubscribe نادرًا ما بيبان فيه مشكلة. وبعد كام سنة على الحال ده، سهل تستنتج إن التنضيف ده شغلانة الـ framework. وهو فعلًا كده، بس للـ subscriptions اللي الـ framework نفسه عملها.
اللي بيحصل فعلًا
Angular بينضّف اللي يعرفه بس
ngOnDestroy بيشتغل، ومعاه كل callback متسجّل في الـ DestroyRef بتاعها. وده بيغطي حاجات كتير: الـ async pipe بيعمل unsubscribe في الـ ngOnDestroy بتاعه، وtoSignal() وeffect() بيسجّلوا التنضيف بتاعهم في الـ DestroyRef بتاع المكان اللي اتعملوا فيه. أما .subscribe() العادي فمابيسجّلش أي حاجة. هو بيرجّع object من نوع Subscription، والـ guide بتاع RxJS بيوصفه إنه resource ينفع يتقفل وليه method واحدة مهمة، unsubscribe(). ولو الكود بتاعك رمى الـ object ده، مش هيفضل حد ينادي الـ method دي.
الـ source هو اللي ماسك الـ component بتاعك
this. وطول ما الـ source عايش، السلسلة دي كلها عايشة. والـ source اللي في root service، أو interval()، أو fromEvent(window, ...)، أو WebSocket، بيعيش قد التطبيق، فبيمسك كل callback عامل subscribe وكل component الـ callbacks دي بتلمسها. والـ garbage collection مايقدرش يفضّي component اتشالت طول ما لسه فيه طريق ليها، والـ callback بيشتغل مع كل قيمة جديدة. وده الـ والخمس toasts، من سطر واحد.
import { Component, inject } from '@angular/core';@Component({ selector: 'app-ticket-page', templateUrl: './ticket-page.html' })export class TicketPage { private readonly notifications = inject(NotificationService); private readonly toast = inject(ToastService); constructor() { // Lives as long as the root service, not as long as this page this.notifications.messages$.subscribe((m) => this.toast.show(m.text)); }}import { Component, inject } from '@angular/core';import { takeUntilDestroyed } from '@angular/core/rxjs-interop';@Component({ selector: 'app-ticket-page', templateUrl: './ticket-page.html' })export class TicketPage { private readonly notifications = inject(NotificationService); private readonly toast = inject(ToastService); constructor() { // Completes when this page is destroyed, so the source lets go this.notifications.messages$ .pipe(takeUntilDestroyed()) .subscribe((m) => this.toast.show(m.text)); }}takeUntilDestroyed() بيعمل complete للـ Observable لما الـ DestroyRef بتاع الـ component يشتغل، وده بيعمل unsubscribe من الـ source ويسيب الـ callback. ولو ناديته في الـ constructor أو في field initializer، بيلاقي الـ DestroyRef لوحده. إنما لو ناديته بعدين، في ngOnInit أو في method، لازم تديهوله، لأنه بيعتمد على الـ عشان يلاقيه.
أأمن subscription هي اللي ماكتبتهاش
subscribe()، لأن إظهار toast ده side effect. بس subscriptions كتير في الـ components مش كده: كل اللي بتعمله إنها تنسخ كل قيمة في field عشان الـ template يعرضها. ودي ممكن تستغنى عن الـ subscription اليدوية خالص وتسيب Angular هو اللي يمسكها.
import { Component, inject } from '@angular/core';import { toSignal } from '@angular/core/rxjs-interop';@Component({ selector: 'app-inbox-badge', template: `<span class="badge">{{ unread() }}</span>`,})export class InboxBadge { private readonly notifications = inject(NotificationService); // No subscribe() to forget: toSignal() unsubscribes on destroy readonly unread = toSignal(this.notifications.unread$, { initialValue: 0 });}toSignal() بيعمل subscribe مرة واحدة، ويحتفظ بآخر قيمة في signal، ويسجّل التنضيف بتاعه بنفسه في الـ DestroyRef بتاع الـ component. والـ initialValue بيغطي اللحظة اللي قبل أول قيمة من الـ stream، فالـ template عمره ما بيشوف undefined.
الـ HTTP subscriptions بتخلص، بس مش دايمًا في الوقت المناسب
HttpClient غالبًا بتعمل complete أول ما الـ response يوصل، وعشان كده الـ guide بتاع الـ HTTP في Angular بيقول إن غالبًا مفيش خطر memory leak لو مانضّفتهاش. بس نفس الـ guide بينصح بقوة إنك تنضّفها لما الـ component تتشال، لسبب تاني: الـ response البطيء ممكن يوصل بعد ما اليوزر يمشي، والـ callback ساعتها بيشتغل على component اتشالت، فيكتب state محدش بيعرضها أو يعمل navigate من صفحة مابقتش موجودة. وكمان الـ unsubscribe بيلغي الـ request لو لسه شغال.
async pipe في الـ template | ||
toSignal() | ||
.subscribe() على call من HttpClient | ||
.subscribe() على stream في service أو interval() أو fromEvent() | ||
.pipe(takeUntilDestroyed()).subscribe() | DestroyRef يشتغل |
تطبقها إزاي في مشروعك
طلّع لستة بكل subscribe() بالإيد دوّر في الـ components والـ directives والـ services على .subscribe(. ولكل واحد، اعرف الـ source بتاعه بيعيش قد إيه، وبيعمل complete لوحده ولا لأ.شيل اللي مش محتاجه القيم اللي بتغذّي الـ template بس خلّيها toSignal()أوasyncpipe. كده مفيش subscription انت مسؤول عنها أصلًا.اقفل الباقي مع الـ component حط takeUntilDestroyed()كآخر operator قبلsubscribe()في الـ constructor أو في field initializer، أو ابعتDestroyRefعملتله inject لما تعمل subscribe فيngOnInitأو في method.اتأكد بـ snapshot كرّر الـ heap snapshot بعد التصليح: ادخل الصفحة واخرج منها، واتأكد إن عدد الـ components رجع لصفر.
الخلاصة
Angular بينضّف الـ asyncpipe وtoSignal()والـ effects والـ callbacks بتاعةDestroyRef، مش الـ subscriptions اللي انت بتفتحها.الـ source اللي بيعيش كتير بيمسك الـ callback بتاعك، والـ component اللي اتشالت وراه، عايشين وشغالين. الـ takeUntilDestroyed()بيربط الـ subscription بالـ component، بس في root service بيعيش قد التطبيق.حتى الـ HTTP subscriptions تستاهل تتنضّف: الـ response المتأخر ممكن يشغّل الـ callback بعد ما الـ component تتشال.
التعليقات (0)