I'm trying to understand how Observables and RxJS works, so this might be not at all the point of how to use them.
I have an Angular2 application and am additionally using RxJS Observables to send events around. Now for a special type of error events, I'd like to know if the event has already been handled by another Subscriber. Multiple Subscribers might exist on the Observable and some might take full responsibility of the event so that others won't get it anymore.
The idea comes from how Routed Events work in WPF. In the event handler you get the RoutedEventArgs parameter, which has a Property Handled:
If setting, set to true if the event is to be marked handled; otherwise false. If reading this value, true indicates that either a class handler, or some instance handler along the route, has already marked this event handled. false.indicates that no such handler has marked the event handled.
Another implementation example would be how the middleware works in the ASP.NET Core Pipeline - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware - You can either call the next middleware or just return a result.
I was thinking about adding the Handled
property to the event I'd throw into the observable pipe, but I'm not sure if it's the idiomatic way of doing this in RxJS.
Typically the way you do this with observables is you don't hand the observable to everyone and everyone subscribes to it. Instead you give each interested party a chance to "add to the pipeline" and then finally subscribe once. There are many ways to do this. The easiest is to not actually give anyone the observable. But instead let them provide you with callbacks:
class Foo {
observable = ...;
callbacks = [];
addCallback(callback) { this.callbacks.push(callback); }
constructor() {
// subscribe to the observable and call any registered callbacks
this.observable.subscribe(e => {
for (const cb of this.callbacks) {
// callback returns true if it has "handled" the event
if (cb(e)) {
return; // do not call any other callbacks
}
}
});
}
}
const foo = new Foo();
// subscriber1 handles "type1" events
foo.addCallback(ev => ev.type === "type1");
// subscriber2
foo.addCallback(ev => ev.type === "type2");
This is the simplest way. There are other ways where Foo
exposes observables for each client and monitors their results to build the pipeline.