Christophe Gigax
Christophe Gigax

Reputation: 3470

Observable .next() to specific Observer

In my Angular 2 app, I have a communication service that I use for broadcasting message over others angular component.

@Injectable()
export class CommunicationService {
    private _broadcast = new Subject<EventParam>();

    broadcast$ = this._broadcast.asObservable();

    public sendEvent(eventParameters: EventParam): void {
        this._broadcast.next(eventParameters); 
    }
}

This works well, but sometimes I know to which component I want to send my message : it's possible with RxJs to send message to a specific observer ?

Upvotes: 0

Views: 4041

Answers (1)

paulpdaniels
paulpdaniels

Reputation: 18663

Observables are meant to be decoupled from Observers, so there isn't a way to really do this by a named look up if that is what you are hoping for. That being said, you can use a filter to do an optional filtering operation.

//In a consumer of your service
communicationService.broadcast$
  //Will allow through events based on an optional field
  .filter(({name}) => !name || name === 'component1')
  .subscribe(x => /**/);

Upvotes: 1

Related Questions