No, the capacity is actually 0. It just looks like you are buffering an element because the collect is first consuming an element, and then delays for 100ms. That allows the flow to emit another element in the meanwhile.
The buffer
function actually creates a second coroutine that allows the flow
and collect
functions to execute concurrently. Without the call to buffer
, each element must be done with the collect
before flow
can continue with the next element, because both functions are executed by the same coroutine.
Let's step through your code to figure out how it happens:
- The flow delays for 1ms, prints
Emitting 1
, emits 1
, and suspends.
- Collect immediately consumes
1
, then starts the delay for 100ms.
- The flow continues because
1
was consumed, delays for another 1ms, prints Emitting 2
, emits 2
, then suspends.
- Collect finishes the delay of 100ms, prints
Consuming 1
, then consumes 2
and delays for another 100ms.
- The flow continues because
2
was consumed, delays for another 1ms, prints Emitting 3
, emits 3
, then suspends.
- Collect finishes the delay of 100ms, prints
Consuming 2
, then consumes 3
and delays for another 100ms.
- Collect finishes the delay of 100ms, prints
Consuming 3
, then finishes collecting.
- The flow continues, and finishes because there's no more elements to emit.
You can read more about buffer
here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/buffer.html
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…