Allow lazy seed for the scan
operator?
#6082
josepot
started this conversation in
Ideas / Feature request
Replies: 1 comment 2 replies
-
Wrap it in const myObservable$ = defer(() => source$.pipe(
scan((acc, event) => {
if (event.type === 'set') {
acc.set(event.payload.id, event.payload)
} else {
acc.delete(event.payload.id)
}
return acc
}, new Map()),
map(entries => Object.fromEntries([...entries])
)) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
In some situations it can be beneficial to have a lazy seed for
scan
. For instance, consider this contrived example:In this example the
scan
operator is mutating its accumulator, which looks like a horribly dangerous thing to do 😱. However, themap
enhancer ensures that the output ofmyObservable$
is an immutable data-structure, so in the end maybe that's not that bad, right?But it is, because now if we unsubscribe from
myObservable$
the garbage collector won't be able to clean thatMap
that we have been mutating, therefore creating a memory-leak. And what's even worse is that if we unsubscribe and later we subscribe again, then the new observer will receive the stale values from the previous observer. So, yeah, as of today mutating the accumulator is always a bad idea...However, if we allowed for a lazy seed, then we could do this:
Which, sure, it looks bad and it's not not a pattern that we would want to promote, of course, but in some cases it can be ergonomic to allow for mutations inside the scan operator, because it can be further improved with an operator that ensures that the result is going to be an immutable data-structure...
Thoughts?
The big caveat with this is that this would be a breaking change, because maybe there are cases where the seed value is actually a function, so in those (probably very rare) cases, the only way to pass a function to the accumulator would be to use the lazy seed to return a function.
Beta Was this translation helpful? Give feedback.
All reactions