2
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?

【Angular】HttpClientのObservableはunsubscribe不要

Last updated at Posted at 2024-07-29

rxjsって難しいけど、うまく書けた時ガッツポーズを決めちゃう泉(@izumin_0401)です。

ブログ記事はこちら

unsubscribeしてる?

Angularでは何かとObservableを扱うと思います。

で、一般的にObservableはngOnDestroyとかでunsubscribeすることが多いと思います。

で、気になって色々調べてみたわけです。

Observableには有限と無限がある

こんなマニアックな情報知ってる人少ないと思うけど、Observableには有限と無限があります。

たとえば、HttpClientのメソッドから返却されるObservableは有限なので、unsubscribeする必要がありません。

逆に(逆でもないけど)、valueChangesなどは無限なのでunsubscribeする必要があります。

有限なObservable

getHeroes(): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl);
}

これは有限なのでunsubscribe不要。

無限なObservable

this.hoge.valueChanges
  .subscribe(x => {
    console.log(x);
  });

これは無限なのでunsubscribe必要。

まとめ

HttpClientを使ったAPIの実行で毎回unsubscribeしてたのは〜どこのどいつだ〜〜い。

私だよ!!

最後に

暇つぶしにTwitterブログもやってるので見てね。

2
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
2
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?