RxJS (Reactive Extensions for JavaScript) adalah library untuk pemrograman reaktif dengan Observable.
Observable Dasar
import { Observable, of, from } from "rxjs"
import { map, filter } from "rxjs/operators"
const numbers$ = of(1, 2, 3, 4, 5)
numbers$.pipe(
filter(n => n > 2),
map(n => n * 10)
).subscribe(value => console.log(value))
// Output: 30, 40, 50
Subscribe
const data$ = this.http.get("/api/data")
data$.subscribe({
next: (data) => console.log(data),
error: (err) => console.error(err),
complete: () => console.log("Selesai"),
})
Operators Penting
map— transformasi datafilter— filter datatap— side effect tanpa mengubah streamswitchMap— cancel request sebelumnya
Unsubscribe dan Memory Leak
Setiap subscribe() yang tidak di-unsubscribe akan terus berjalan meski komponen sudah di-destroy — ini sumber memory leak paling umum di Angular. Ada tiga strategi aman:
1. async pipe di template — otomatis cleanup:
users$ = this.api.getUsers();
<div *ngFor="let u of users$ | async">{{ u.nama }}</div>
Saat komponen destroy, async pipe otomatis unsubscribe. Gaya paling direkomendasikan.
2. takeUntilDestroyed() (Angular 16+):
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
this.api.getUsers()
.pipe(takeUntilDestroyed())
.subscribe(data => this.users = data);
Otomatis cleanup saat injection context (komponen/service) destroy.
3. Manual di ngOnDestroy:
private sub = new Subscription();
ngOnInit() {
this.sub.add(this.api.getUsers().subscribe(data => this.users = data));
}
ngOnDestroy() {
this.sub.unsubscribe();
}
💡 Rule of thumb: utamakan
asyncpipe. Kalau tidak memungkinkan, pakaitakeUntilDestroyed(). Manual unsubscribe hanya kalau dua opsi di atas tidak cocok.