-
Notifications
You must be signed in to change notification settings - Fork 22
Flows: Collecting Latest
Devrath edited this page Jan 19, 2024
·
3 revisions
- Consider a scenario, Where the flow has emitted the emission, and the consumer has still not finished processing the consumption.
- Immediately another emission is sent
- So now the first emission is canceled in between and the new emission is received and starts processing
Note in the output 3 emissions have taken place, those 3 emissions are in process but only the latest which is the last one is completely processed
Emission -> 0
Emission -> 1
Emission -> 2
Processing emission -> 0
Processing emission -> 1
Processing emission -> 2
Processed emission -> 2
private val collectLatestDemoFlow = flow {
// Make 10 emissions in iteration
repeat(3){
// Give some delay
println("Emission -> $it")
emit(it)
}
}.flowOn(Dispatchers.Default)
fun collectLatest() = viewModelScope.launch{
// It will show the time taken to execute this block of code
val time = measureTimeMillis {
collectLatestDemoFlow.collectLatest {
println("Processing emission -> $it")
delay(1000)
println("Processed emission -> $it")
}
}
println("Time Taken:-> $time")
}