Building a generic element counter that transiently counts the elements that go through a fs2 Stream
During our migration from Akka to the Typelevel stack, we're switching from Akka Streams to fs2.
For one of our services, we needed something that counts the elements that go through a stream and writes a metric for it.
Previously that was done using an AtomicInteger, which worked alright but now we're in a pure functional land and writing metrics as well as using mutable variables is considered impure and has to be implemented as an IO action, which rules out AtomicInteger (one could use cats.effect.Ref as an almost-identical replacement, but we can do better than that).
Implementing this turned out to be a nice little exercise, so I thought it makes sense to write down how we did it.
So, suppose we have a stream of product data: