I have a subscription that I want to use to signal events, in a piece of middleware code. So I have one thing that wants to subscribe an observable, and another thing that's not quite an observable.
I thought about using Subjects for this - that's what they seem to be for:
const repeater = new Rx.Subject();
function subscribe(observer) {
return repeater.subscribe(observer);
}
// in some other function, call repeater.next(val)
But then I started looking at what regular subscribe() calls return. I could do this instead:
let sub = null;
function subscribe(observer) {
return Rx.Observable.create((o) => sub = o);
}
// elsewhere sub.next(val)
But also?
let unsub = null;
function subscribe(observer) {
unsub = Rx.Observable.create(() => false).subscribe(observer)
}
// elsewhere unsub.next(val)
all of these things will signal val to the subscriber. The weird thing that I don't understand here is the subscription return having a next()
available to it - I thought next()
only lived on the observer in the Observable context.
I need to keep a handle on the unsubscription doodad no matter what - when the middleware is torn down, I need to signal stream completion and release some resources. It was surprising to me that unsub had a functioning next.
This signals to me that there's some bit of RxJS that I just plain don't grok yet, in terms of Observers and Observables and Subjects and so on. In general, I understand how to wire event sources and other similar things into an observable stream. It's really just in the context of building an observable stream out of a boring function call - whenever the function is called by an external library, this stream signals an updated observable.