Skip to content

Flows: Buffering

Devrath edited this page Jan 19, 2024 · 2 revisions

Where buffering can be useful

  • Consider a scenario when we encounter a flow and usually, the rate at which the flow is produced is faster than the rate at which the flow is consumed.
  • Meaning consumption takes more time than emission
  • Using buffering we can improve this in a better way here.

Observation

Time Taken:-> 1122 // Without buffer
Time Taken:-> 1088 // With buffer
  • Note when we add the buffer the time taken overall is reduced
  • This is because, without a buffer after each emission, it takes time to process the emission but since we give some buffer limit, It will keep emitting to the buffer quantity and start collection.
  • Thus if we increase the buffer quantity, the time decreases even more.

Code

    private val bufferDemoFlow = flow {
        // Make 10 emissions in iteration
        repeat(10){
            // Give some delay
            delay(50)
            println("Emission -> $it")
            emit(it)
        }
    }.flowOn(Dispatchers.Default)

   fun buffering() = viewModelScope.launch{
        // It will show the time taken to execute this block of code
        val time = measureTimeMillis {
            bufferDemoFlow.buffer(5).collect {
                delay(100)
                println("Collection -> $it")
            }
        }
        println("Time Taken:-> $time")
    }
Clone this wiki locally