Counting the number of values emitted before the Observable completes?

1722 views node.js
-2

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

o.pipe(count).subscribe(count=>
  expect(count).toEqual(4));

Thoughts?

answered question

1 Answer

1

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?

JD

Please login first before posting an answer.