Should I unsubscribe from Cold Observable?

后端 未结 3 1688
误落风尘
误落风尘 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:08

    It is definitely the best practice to free the used memory in javascript just like other programming languages.

    Since you are using angular 2 you can use ngOnDestroy life cycle hook to achieve as this method is executed when the component loses its scope.

    Assuming that you use a below snippet to subscribe to a data

    subscription = this._http.getMethod('...')
                        .subscribe(response => this.responses = response,
                        error =>this.errorMessage = error)
    

    You should be using importing OnDestroy lifecycle hook from angular/core using an import statement.

    import { OnDestroy } from '@angular/core'
    

    implement OnDestroy in your component as

    export class MyComponent implements onDestroy {
         .............
    
    
         ngOnDestroy() {
              this.subscription.unsubscribe();
         }
    
    }
    

提交回复
热议问题