Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable to a observable

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
    }
);
like image 515
Zander17 Avatar asked Aug 27 '26 19:08

Zander17


2 Answers

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.

Edit: See the answer by ThnkingMedia

I'm not so sure if you can do it with the syntax you're looking for, but you could probably do something along the lines of

let flag: boolean = someProperty;
this._socket.onMessage.subscribe(
    (message) => {
        if (flag) { // do something
        }
    }
);

Also, I'm pretty sure on your Observable you can use a filter() call. So the Observable could probably change

myObservable.filter(...).map(...).subscribe(....)
//where myObservable is the Observable object you're working with    
like image 23
SaxyPandaBear Avatar answered Aug 30 '26 10:08

SaxyPandaBear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!