Should I unsubscribe from Cold Observable?

后端 未结 3 1695
误落风尘
误落风尘 2021-01-07 00:33

I know that it\'s good practice to unsubscribe from Observable to prevent memory leak.

But if it\'s Cold Observable

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 01:25

    Since Cold Observables are finite you dont have to unsubscribe.

    Unsubscribe when:

    • Infinite Obesrvables, ex. interval()
    • If subscribed to (Subject, BehaviorSubject, ReplaySubject, AsyncSubject)

    In case of ReplaySubject you should unsubscribe if it cache life time is not provided

    In case of AsyncSubject you should unsubscribe if it is not completed

    • Websocket stream
    • Abstract control ex. valueChanges()
    • Renderer2.listen()
    • Events streams ex. formEvent()
    • NgRx Store

    Do not unsubscribe when:

    • If stream is ending himself ex. of('1','2')
    • Router events, all Observables from Router are unsubscribing them self
    • AsyncPipe
    • Finite Observable ex. http.get()
    • EventEmmiter

    Subscribe have to be unsubscribed if it would not hit complete or error.

    If I am wrong or missing something please let me know. Thanks ;)

提交回复
热议问题