Should I unsubscribe from private streams defined in components? I tested their destruction with WeakMap

Issue

This Content is from Stack Overflow. Question asked by hellohello

For example, I:

  1. Created a class with private Subject and WeakMaps to add Subject and Subscription
    const subjectsMap = new WeakMap();
    const subscriptionsMap = new WeakMap();
    
    class Test {
      #privateSubject = new BehaviorSubject(false);
      
      constructor() {
        subscriptionsMap.set(this.#privateSubject.subscribe(console.log), true);
        subjectsMap.set(this.#privateSubject, true);
      }
    }
  1. Created a new Test instance
let test = new Test()
  1. Checked my Weakmaps
console.log(subjectsMap)
> WeakMap {BehaviorSubject => true}

console.log(subscriptionsMap)
> WeakMap {SafeSubscriber => true}
  1. Deleted the reference to my Test instance
test = null
  1. Checked my WeakMaps and voila
console.log(subjectsMap)
> WeakMap {}

console.log(subscriptionsMap)
> WeakMap {}

My Subject and Subscription are destroyed. So why do I need to unsubscribe from them in the component?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?