I want to display partial results of an analysis as the data comes in. It would be very inefficient to recompute for each new value (as with 'scan'). However, in this case, I can do the analysis on chunks of the data and combine those results. So I've been using 'window' to break up the data and then 'scan' to combine the results of each window calculation. The result is itself an observable, so it would be very natural to emit that as a nested observable. Also, the next step in the process works really well when consuming observables.
However, I couldn't get this to work as I expected. (I did make it work with an awkward step of turning the inner observables into arrays and later back into observables.) It seems there is something I don't understand about "window" and/or "scan".
Here are two examples that differ in how I produce the nested observable. I'd have expected the following two examples to give the same result, but they do not.
In the first, I create the nested observable directly. In the second, I create it with the window operation. Then, in both cases, I apply the same scan to the nested observable.
This behaves as I expected:
rxjs.from([rxjs.from([1, 2]), rxjs.from([3, 4])])
.pipe(
ops.scan((acc, curr) => rxjs.merge(acc, curr), rxjs.from([]))
).subscribe(win => win.subscribe(
x => console.log(JSON.stringify(x)), e => console.log("error"), () => console.log("|")),
e => console.log("outer error"), () => console.log("outer |"))
With each emitted observable, I see the accumulation of the values of the previous one followed by the new ones.
1 2 | 1 2 3 4 |
I expected this next one to produce the same result, but it doesn't:
rxjs.from([1, 2, 3, 4])
.pipe(
ops.windowCount(2),
ops.scan((acc, curr) => rxjs.merge(acc, curr), rxjs.from([]))
).subscribe(win => win.subscribe(x => console.log(JSON.stringify(x)), e => console.log("error"), () => console.log("|")),
e => console.log("outer error"), () => console.log("outer|"))
It seems to effectively ignore the scan operation and emits the original windows,
1 2 | 3 4 |
What am I missing? What would a conventional solution to this look like? Thanks!