반응형
Subscription(구독)은 일반적으로 실행중인 Observable과 같이 사용후 처분가능한 리소스를 나타냅니다. Subscription은 unsubscribe라는 구독이 보유하고 있는 리소스를 처분하는 인자없는 중요한 메소드를 가지고 있습니다. RxJS의 이전 버전에서는 Subscription을 Disposable로 불렸습니다.
import { interval } from 'rxjs';
const observable = interval(1000);
const subscription = observable.subscribe(x => console.log(x));
// Later:
// This cancels the ongoing Observable execution which
// was started by calling subscribe with an Observer.
subscription.unsubscribe();
Subscription은 본질적으로 리소스를 릴리즈하거나 Observable의 실행을 취소하는 unsubscribe()라는 function을 가집니다.
Subscription은 unsubscribe() 한번호출로 여러 Subscription을 구독해지 할 수 있도록 합칠 수 있습니다. 한 Subscription을 다른 Subscription에 adding 함으로서 합칠 수 있습니다.
import { interval } from 'rxjs';
const observable1 = interval(400);
const observable2 = interval(300);
const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));
subscription.add(childSubscription);
setTimeout(() => {
// subscription 과 childSubscription 둘다 구독해지
subscription.unsubscribe();
}, 1000);
콘솔에서 아래와 같은 실행결과를 볼 수 있습니다.
second: 0
first: 0
second: 1
first: 1
second: 2
Subscription에는 추가했던 자식 Subscription의 추가를 취소하는 remove(otherSubscription)라는 메소드도 가지고 있습니다.
출처
이글은 RxJS 공식 사이트 Subscription, CC BY 4.0 페이지의 번역물 입니다.
'JavaScript > RxJS' 카테고리의 다른 글
| RxJS - Scheduler (1) | 2019.11.03 |
|---|---|
| RxJS - Subject (0) | 2019.11.03 |
