In previous Blog post I demonstrated takeuntil operator using a start, stop interval example.

In this Blog post I’ll demonstrate the scan operator using same previous example to start and then stop a stream and finally resume the stream where I left it.

One incorrect way to do this will be something like this:

This will work but its not the proper way to do things.

The proper way to gather and collect data in RxJS is to use the .scan() operator.

The scan operator works just like the reduce function in JavaScript arrays. It takes a function and on initializer. The initializer in this example is just going to be a count of 0 . Then, that comes into this function as an accumulator, in this case acc parameter.

When this function is called, I get this acc as this first argument.

I’ll return a new object with a property called “count,” which is acc.count + 1.

This function now is just going return an object with a count on it. It’s going to take previous accumulator and increment by 1 each time. Then value is going to be pushed and logged out into the subscription.

sample code

LEAVE A REPLY

Please enter your comment!
Please enter your name here