Counting the number of values emitted before the Observable completes?

1722 views node.js

Attempting to verify that an observable emits a certain number of events before it completes. This is pseudo code:



answered question

1 Answer


The count operator works as follows:

Counts the number of emissions on the source and emits that number when the source completes (source)

So you can use it like so:

obs.pipe(count()).subscribe(totalEmissions => expect(totalEmissions).toEqual(4))

Note that you can't really measure how many events occured before the original observable completed, because if it didn't complete then you didn't finish counting!

You can, however, take note of the "index" of each emission using tap:

let count = 0
obs.pipe(tap(() => console.log("emitted! Index: " + count++))).subscribe(obsValue => {/*...*/})

I'm not sure which is your use case, but that's how you can do it.

posted this

Have an answer?


Please login first before posting an answer.