[Fixed] Pass a variable to a observable

Issue

I’m currently using an observable in the following way:

this._socket.onMessage.subscribe(
    (message) => {

    }
);

which works fine! However, Would it be possible to pass a variable to the observable that would allow for some logic?

For example by passing a variable “name” to onMessage, I could subscribe only to events whos name is something specific? Like this:

this._socket.onMessage(name-variable).subscribe(
    (message) => {
        // only get events that is related to the name-variable
    }
);

Solution

You have to create helper functions that yield the desired effect.

public getMessagesForName(name: string): Observable<any> {
    return this._socket.onMessage.filter((message) => {
        return message.name === name;
    });
}

The more advanced approach would be to create your own class that extends one of the Subject classes. Like EventEmitter or Subject and add the helper functions there. You would then just apply the filter to the this reference.

Here’s an example:

 class MessageEvent extends EventEmitter<MessageData> {
       public forName(name: string): Observable<MessageData> {
          return this.filter((message) => {
               return message.name === name;
          });
       }
 }

It all depends on how much re-use you need.

Leave a Reply

(*) Required, Your email will not be published