Skip to content

Flows: Conflation

Devrath edited this page Jan 19, 2024 · 3 revisions

Where conflation can be useful

  • We use the conflation when it is not necessary for all the emissions from the flow to be collected.
  • It gets the most recent elements and ignores the other elements.

Observation

  • Note 0 and 4 are printed 0 was first and 4 was the latest, no other elements since we used take-operator

code

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

    fun conflating() = viewModelScope.launch{
        // It will show the time taken to execute this block of code
        val time = measureTimeMillis {
            conflatingDemoFlow.take(5).conflate().collect {
                delay(100)
                println("Collection -> $it")
            }
        }
        println("Time Taken:-> $time")
    }

output

Emission -> 0
Emission -> 1
Emission -> 2
Emission -> 3
Emission -> 4
Emission -> 5
Emission -> 6
Emission -> 7
Emission -> 8
Emission -> 9
Collection -> 0
Collection -> 4
Clone this wiki locally