MutableSharedFlow takes 3 parameters: replay, extraBufferCapacity and onBufferOverflow. What is the difference between replay and extraBufferCapacity?
The documentation mentions the following:
replay - the number of values replayed to new subscribers (cannot be negative, defaults to zero).
extraBufferCapacity - the number of values buffered in addition to replay. emit does not suspend while there is a buffer space remaining (optional, cannot be negative, defaults to zero).
I don't understand exactly the difference between the 2 and when we would need extraBufferCapacity > 0. Is extraBufferCapacity just an additional replay capacity for emitters?
CodePudding user response:
Is extraBufferCapacity just an additional replay capacity for emitters?
The "replay" terminology only really makes sense for subscribers, not emitters. The replay
parameter defines how many past values new subscribers will receive upon subscribing. It obviously implies that those values need to be stored, so the overall buffer needs to be at least this big.
However, the buffer size as a whole impacts emitters. The exact consequence of a full buffer depends on onBufferOverflow
, but this buffer size can be used to control backpressure on emitters (slowing them down) or how we drop messages. With a larger buffer, you can allow emitters to have bursts of emissions without slowing them down, like any regular buffer.
Now, choosing to have a larger buffer shouldn't force you to replay those buffered values to new subscribers, hence the extraBufferCapacity
. With extraBufferCapacity > 0
, you can define a buffer of any desired size without also forcing you to replay as many values, simply by using the formula:
bufferSize = replay extraBufferCapacity
You could for instance decide to replay no values at all to new subscribers, but still allow bursts from emitters by having some (non-replayed) buffer.