Miguel Moura
Miguel Moura

Reputation: 39454

Subscribe Observable and get Events of specific type

I have the following Angular service:

export class EventService {

  private subject = new Subject<Event>();

  send(code: EventCode, data?: any) {
    this.subject.next(event);
  }

  clear() {
    this.subject.next();
  }

  get(): Observable<Event> {
    return this.subject.asObservable();
  }

}

Where Event and EventCode are:

export class Event {
  code: EventCode;
  data: any;
  constructor(code: EventCode, data?: any) {
    this.code = code;
    this.data = data;
  } 
} 

export enum EventCode {
  Created,
  Deleted,
  Updated
}

Then I use it as follows:

this.eventService.get().subscribe((event: Event) => { 
  // Do something 
});

I would like to be able to subscribe only Events with a specific EventCode.

Or maybe react only to Events with a specific EventCode ...

It this possible? How can I do this?

Upvotes: 1

Views: 1401

Answers (1)

The Head Rush
The Head Rush

Reputation: 3356

Before we get started, this:

this.eventService.get().subscribe((event: Event) => { 
  // Do something 
});

will leak memory when the component destroys because you don't unsubscribe. Do this instead.

export class MyComponent implements OnInit, OnDestroy {
  // store subscrition
  private eventServiceSubscription: Subscription;

  ngOnInit() {
        this.eventServiceSubscription = this.eventService.get().subscribe((event: Event) => {
          // check event code
          if(event.code === 'someEventCode') {
            // process event
           }
         });
   }

   ngOnDestroy() {
     this.eventServiceSubscription.unsubscribe();
   }
}

Upvotes: 1

Related Questions