Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generally use unsubscribe on observables #105

Open
boeckMt opened this issue Mar 9, 2022 · 1 comment
Open

Generally use unsubscribe on observables #105

boeckMt opened this issue Mar 9, 2022 · 1 comment
Assignees

Comments

@boeckMt
Copy link
Member

boeckMt commented Mar 9, 2022

There are a lot of open subscriptions, which we should unsubscribe on ngOnDestroy


Maybe we can use something like https://github.com/wardbell/subsink

So in general a instance which collects all the stuff and unsubscribes from it

import { Subscription } from 'rxjs';

export class UnSub {
  private privSubs: Subscription[] = [];
  public get subs(): Subscription[] {
    return this.privSubs;
  }


  public set subs(value: Subscription | Subscription[]) {
    if (Array.isArray(value)) {
      this.privSubs.push(...value);
    } else {
      this.privSubs.push(value);
    }
  }


  public unsubscribe(): void {
    this.subs.forEach(s => s.unsubscribe());
  }
}
@boeckMt
Copy link
Member Author

boeckMt commented Mar 9, 2022

This implementation can be used for rx subscriptions and also for ol observables.

import { Subscription } from 'rxjs';
import { unByKey } from 'ol/Observable';
import { EventsKey } from 'ol/events';

export class CollectSub {
  protected privSubs: Array<Subscription | EventsKey> = [];
  public get subs(): Array<Subscription | EventsKey> {
    return this.privSubs;
  }


  public set subs(value: Subscription | EventsKey | Array<Subscription | EventsKey>) {
    if (Array.isArray(value)) {
      this.privSubs.push(...value);
    } else {
      this.privSubs.push(value);
    }
  }

  public unsubscribe(): void {
    this.subs.forEach(s => {
      console.log(s)
      if (s instanceof Subscription) {
        s.unsubscribe();
      } else if ('listener' in s && 'target' in s && 'type' in s) {
        unByKey(s);
      }
    });
  }
}

Usage

this.collectSub.subs = this.highlightedFeatures$.subscribe((features: Feature<Geometry>[]) => {
   ...
});

this.collectSub.subs = this.mapSvc.map.on('click', () => {
  ...
});
...


ngOnDestroy(): void {
   this.collectSub.unsubscribe();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants