0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【RxJS】購読の解除

0
Posted at

結論

  • subscribe() はObservableの購読を開始するだけでなく、戻り値として Subscription オブジェクトを返す
  • このオブジェクトの unsubscribe() を呼び出すことで、その購読を解除できる
  • 購読を解除すると、その購読者は以降通知される値を受け取らなくなる
  • つまり、Subscriptionオブジェクトを使うことで、購読を自分のタイミングで終了できる

詳細

subscribe() の戻り値

const subscriptionA = subjectA.subscribe((value) => {
  console.log('受信:', value);
});

subscribe() は購読を開始するだけでなく、戻り値にSubscriptionオブジェクトを返す

unsubscribe() で購読解除する

  • Subscriptionオブジェクトには unsubscribe() というメソッドがある
  • これを呼び出すと、その購読者は値を受け取らなくなる
const subjectA = new Subject<number>();

// 1:購読する
const subscriptionA = subjectA.subscribe((value) => {
  console.log('購読者A:', value);
});

// 2:値を発行する
subjectA.next(100);

// 3:購読解除する
subscriptionA.unsubscribe();

// 4:もう一度値を発行する
subjectA.next(200);
購読者A: 100

subscriptionA.unsubscribe() で、Aの購読を解除したあとに値を発行しても、Aは購読解除済みなので受け取らない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?