You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 line
1.8KB

  1. import { Injectable } from '@angular/core';
  2. import { Observable, Observer, Subscription } from 'rxjs';
  3. import { filter, share } from 'rxjs/operators';
  4. export class EventWithContent<T> {
  5. constructor(
  6. public name: string,
  7. public content: T,
  8. ) {}
  9. }
  10. /**
  11. * A utility class to manage RX events
  12. */
  13. @Injectable({
  14. providedIn: 'root',
  15. })
  16. export class EventManager {
  17. observable: Observable<EventWithContent<unknown> | string>;
  18. observer?: Observer<EventWithContent<unknown> | string>;
  19. constructor() {
  20. this.observable = new Observable((observer: Observer<EventWithContent<unknown> | string>) => {
  21. this.observer = observer;
  22. }).pipe(share());
  23. }
  24. /**
  25. * Method to broadcast the event to observer
  26. */
  27. broadcast(event: EventWithContent<unknown> | string): void {
  28. if (this.observer) {
  29. this.observer.next(event);
  30. }
  31. }
  32. /**
  33. * Method to subscribe to an event with callback
  34. * @param eventNames Single event name or array of event names to what subscribe
  35. * @param callback Callback to run when the event occurs
  36. */
  37. subscribe(eventNames: string | string[], callback: (event: EventWithContent<unknown> | string) => void): Subscription {
  38. if (typeof eventNames === 'string') {
  39. eventNames = [eventNames];
  40. }
  41. return this.observable
  42. .pipe(
  43. filter((event: EventWithContent<unknown> | string) => {
  44. for (const eventName of eventNames) {
  45. if ((typeof event === 'string' && event === eventName) || (typeof event !== 'string' && event.name === eventName)) {
  46. return true;
  47. }
  48. }
  49. return false;
  50. }),
  51. )
  52. .subscribe(callback);
  53. }
  54. /**
  55. * Method to unsubscribe the subscription
  56. */
  57. destroy(subscriber: Subscription): void {
  58. subscriber.unsubscribe();
  59. }
  60. }