How can I tell if an Observable is running or not?
You should think of Observables like pipes: you cannot tell what is happening inside of them by looking at the outside.
The question should be rephrased as, given an Observable, how can I create another Observable that emits true when a the first Observable is still running and false when it is not.
First, consider the following operator:
function activity() {
return pipe(
mapTo(0),
startWith(1),
endWith(-1),
catchError(() => of(-1)),
);
}
This will emit 1, then 0 every time the source Observable emits, and then -1 when it finalizes, successfully or not. In marble terms:
source: ---a--b--c---.
result 1--0--0--0--(-1).
Why that weird protocol? Well, mostly because I have a theory that activity() will be useful later, but you can see that
result 1--0--0--0--(-1).
Why that weird protocol? Well, mostly because I have a theory that activity() will be useful later, but you can see that
function runningSum() {
return scan((acc, v) => acc + v, 0);
}
source.pipe(runningSum());
will emit 1 whenever the source Observable is running and 0 when it is not, which would be easy to convert to the desired Observable. But, I have other plans. Consider this:
return scan((acc, v) => acc + v, 0);
}
source.pipe(runningSum());
will emit 1 whenever the source Observable is running and 0 when it is not, which would be easy to convert to the desired Observable. But, I have other plans. Consider this:
const monitor = new ReplaySubject();
const isMonitorBusy = monitor.pipe(
mergeMap(obs => obs.pipe(activity())),
runningSum(),
map(v => !!v),
distinct(),
shareReplay(1),
);
Now, you can watch as many Observables as you want, just by calling monitor.next() with each Observable you're interested in.
What? Too complicated and you want me to just answer the question? Man, you people are no fun at all...
function isBusy() {
return pipe(
filter(Boolean.false), // ie. filter out everything
startWith(true),
endWith(false),
catchError(() => of(false)),
);
}
Here is the code.
Next time: “How do I space out emissions in time?”
Comments
Post a Comment