Search code examples
angularobservablesubscriptionunsubscribe

What happened with subscription if subject was destroyed in angular 2+?


UPDATE more details about observable usage

I've need service because checkboxcell component can't use @Output() property. This happened becaues of wrong usage with ag-grid api - renderer component was used as editor. It can't be corrected at this moment.

@Component({
    ...
    template: `<mat-checkbox (change)="onChanged($event)"></mat-checkbox>`
})
export class CheckboxCellComponent implements ICellRendererAngularComp {
    ...
    //each component that use checkboxcell provide own instance of PermissionChange
    constructor(private permissionChange: PermissionChange) {

    }
    public onChanged({ checked }): void {
         //use observable
         this.permissionChange.changeEvent.next();
    }
}

ORIGINAL question

I have a simple service

export class PermissionChange {
    public changeEvent: Subject<void>;
    constructor() {
        this.changeEvent = new Subject<void>();
    }
}

And component, that use the service:

@Component({
    ...
    providers: [PermissionChange]
})
export class ...Component implements OnInit {
    constructor(
        private permissionChange: PermissionChange,
    ) { }

    public ngOnInit(): void {
        //subscription
        this.permissionChange.changeEvent.subscribe(() => {...});
    }
}

PermisionChange is personal provider for this component => instance of PermisionChange will be destroyed in the moment when component will be destroyed => changeEvent observable will be destroyed too. So maybe there is no need to unsubscribe, maybe subscribtion will be destroyed too? But I don't know how to check it.


Solution

  • You don't need to unsubscribe in this case: the parent component, the child components and the service instance will all be destroyed and be eligible to garbage collection when the parent component is destroyed.

    Nothing live will keep a reference to the Subject in the service, and it will thus be eligible to GC, too.