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
}
);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With