RxJS & Observables
Async Pipe
| async — Automatic Subscription
💡 Async pipe ek autopilot hai — normally subscribe/unsubscribe manually karna padta hai (jaise plane khud udana), async pipe SAB KUCH khud handle kar leta hai (subscribe karta hai, aur component destroy hone par AUTOMATICALLY unsubscribe bhi) — hands-free.
| async pipe TEMPLATE mein Observable ko DIRECTLY use karne deता hai, bina manual .subscribe() ke — AUTOMATICALLY subscribe karta hai, latest value display karta hai, AUR component destroy hone par AUTOMATICALLY unsubscribe bhi kar deta hai — memory leaks se bachने ka SABSE clean tareeka.
export class UserProfileComponent {
user$ = this.userService.getCurrentUser(); // Observable, subscribe NAHI kiya
constructor(private userService: UserService) { }
}
// Template — async pipe khud subscribe karta hai:
// <div *ngIf="user$ | async as user">
// <p>Name: {{ user.name }}</p>
// <p>Email: {{ user.email }}</p>
// </div>
// Koi ngOnDestroy/unsubscribe LIKHNE ki zaroorat nahi!🚰
Async pipe ek autopilot hai — normally subscribe/unsubscribe manually karna padta hai (jaise plane khud udana), async pipe SAB KUCH khud handle kar leta hai (subscribe karta hai, aur component destroy hone par AUTOMATICALLY unsubscribe bhi) — hands-free.
1 / 6
⚡ Quick Recap
- | async = automatic subscribe + automatic unsubscribe
- Memory leaks se bachने ka safest, cleanest tareeka
- as variableName = ek baar resolve karके reuse karo (multiple subscriptions avoid)
Is page mein (2 subtopics)
SAME Observable ko MULTIPLE baar | async karna (template mein alag-alag jagah) MULTIPLE, SEPARATE subscriptions create karta hai — performance ke liye BAD (especially HTTP calls ke liye). as variableName pattern se EK subscription REUSE karo.
<!-- BAD — 3 SEPARATE subscriptions: -->
<!-- <p>{{ (user$ | async)?.name }}</p>
<p>{{ (user$ | async)?.email }}</p>
<p>{{ (user$ | async)?.age }}</p> -->
<!-- GOOD — EK subscription, reuse karo: -->
<!-- <div *ngIf="user$ | async as user">
<p>{{ user.name }}</p>
<p>{{ user.email }}</p>
<p>{{ user.age }}</p>
</div> -->Common Mistake: Multiple | async usage (SAME Observable ke liye) ek COMMON performance mistake hai — HTTP Observable ke liye ye MULTIPLE API calls trigger kar sakta hai! as variableName pattern se HAMESHA bachो.
| async ko doosre pipes ke SAATH CHAIN kar sakte ho — Observable resolve hone ke BAAD, result ko FURTHER transform karo (jaise date formatting).
<!-- <p>{{ (lastUpdated$ | async) | date:'short' }}</p> -->
<!-- Pehle async pipe Observable resolve karta hai (Date object),
phir date pipe use format karta hai -->Tip: Pipe chaining LEFT-TO-RIGHT process hota hai — async pipe PEHLE chalta hai (Observable → value), phir baaki pipes us RESOLVED value par apply hote hain.