Pass a variable to a observable

Viewed 14852

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
    }
);
5 Answers

For anybody needing this, this is how you can pass variables to observables and use the observer at the same time:

function onMessage(message): Observable<any>{
   return new Observable(observer => {
      socket.message(message).subscribe(result => {
         observer.next(result); 
      });
   });
}

This way you can use it like this:

onMessage('Hello World').subscribe(msg => {
   alert(msg);
});
Related