Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

Kotlin flow buffer capacity

I have a question about Kotlin flow buffer capacity. The following code:

import kotlinx.coroutines.flow.*

suspend fun main() = coroutineScope {
    flow { 
        for (i in 1..3) { 
            println("Emiting $i")
            emit(i) 
        }
    }.buffer(0)
    .collect { 
        value -> 
            delay(100)
            println("Consuming $value")
    }
}

generates the following output:

Emiting 1
Emiting 2
Consuming 1
Emiting 3
Consuming 2
Consuming 3

If I remove the buffer, the result is:

Emiting 1
Consuming 1
Emiting 2
Consuming 2
Emiting 3
Consuming 3

Shall I assume that when the capacity is 0 means that is actually 1?

question from:https://stackoverflow.com/questions/65952256/kotlin-flow-buffer-capacity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. The flow delays for 1ms, prints Emitting 1, emits 1, and suspends.
  2. Collect immediately consumes 1, then starts the delay for 100ms.
  3. The flow continues because 1 was consumed, delays for another 1ms, prints Emitting 2, emits 2, then suspends.
  4. Collect finishes the delay of 100ms, prints Consuming 1, then consumes 2 and delays for another 100ms.
  5. The flow continues because 2 was consumed, delays for another 1ms, prints Emitting 3, emits 3, then suspends.
  6. Collect finishes the delay of 100ms, prints Consuming 2, then consumes 3 and delays for another 100ms.
  7. Collect finishes the delay of 100ms, prints Consuming 3, then finishes collecting.
  8. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...