takeUntilDestroyed() 연산자는 Angular 프레임워크에서 옵저버블 구독 관리를 간편하게 처리하기 위해 사용되는 RxJS 연산자입니다. 이 연산자를 사용하면 옵저버블의 구독을 자동으로 해제할 수 있으며, 주로 OnDestroy 이벤트와 함께 활용됩니다.
아래에 takeUntilDestroyed()의 사용 예시를 제시합니다:
destroyed$라는 Subject 또는 BehaviorSubject를 생성합니다.private destroyed$ = new Subject<void>();
destroyed$.next()를 호출하여 파괴 신호를 방출합니다.ngOnDestroy() {
this.destroyed$.next();
}
takeUntilDestroyed(destroyed$)을 사용하여 구독을 관리합니다.toObservable(this.type)
.pipe(
takeUntilDestroyed(this.destroyed$),
switchMap((type) => {
return this.httpService.get<ITermDTO[]>(`terms?type=${type}`);
})
)
.subscribe((data) => {
// 데이터 처리 로직
});
위 코드에서 takeUntilDestroyed(this.destroyed$)은 destroyed$가 방출될 때까지 옵저버블 스트림을 유지하고, 파괴 신호가 발생하면 자동으로 구독이 해제됩니다. 이로써 메모리 누수를 방지하고 애플리케이션 성능을 향상시킬 수 있습니다.
takeUntilDestroyed() 연산자는 다른 RxJS 연산자와 함께 유용하게 활용할 수 있습니다. 예를 들어, filter()나 map()과 같은 연산자를 조합하여 옵저버블의 값을 필터링하거나 변환할 수 있습니다.
toObservable(this.type)
.pipe(
takeUntilDestroyed(this.destroyed$),
filter((type) => type !== 'invalid'),
map((type) => type.toUpperCase()),
switchMap((type) => {
return this.httpService.get<ITermDTO[]>(`terms?type=${type}`);
})
)
.subscribe((data) => {
// 데이터 처리 로직
});
위 코드에서 filter() 연산자는 'invalid'이 아닌 유효한 타입만 허용하고, map() 연산자는 타입 값을 대문자로 변환합니다. 그 후에는 switchMap()을 사용하여 HTTP 요청을 실행합니다.
이렇게 하면 파괴 신호가 발생하기 전까지 필터링 및 변환 작업이 적용된 상태로 옵저버블 스트림이 유지됩니다.