Skip to content

Flattening Flow: FlatMapLatest or FlattenLatest

Devrath edited this page Jan 23, 2024 · 1 revision

What it does

Here when an emission has happened and before it is consumed if another emission happens, The previous emission is canceled and new emission is used

Output

<Emitted> -->0
<Emitted> -->1
collected: ---> Current string no -->0 at the threadDefaultDispatcher-worker-4
<Emitted> -->2
<Emitted> -->3
collected: ---> Current string no -->1 at the threadDefaultDispatcher-worker-4
<Emitted> -->4
collected: ---> Current string no -->2 at the threadDefaultDispatcher-worker-4
collected: ---> Current string no -->3 at the threadDefaultDispatcher-worker-4
collected: ---> Current string no -->4 at the threadDefaultDispatcher-worker-4

Code

class FlattenFlowsDemoVm @Inject constructor(
    @ApplicationContext private val context: Context,
) : ViewModel() {

    private val rootScope = CoroutineScope(context = Dispatchers.IO)

    /**
     * Flow of integers
     */
    fun generateIntegers() = flow {
        repeat(100){
            delay(1000)
            emit(it)
        }
    }


    /**
     * Generate a flow of strings
     */
    fun generateFlowOfStrings(value : Int) = flow {
        val content = "Current string no -->$value at the thread${Thread.currentThread().name}"
        println("<Emitted> -->$value")
        emit(content)
    }



    fun flatMaplatest() = rootScope.launch(CoroutineName("flatMapLatest")){
        generateIntegers()
            .take(5)
            .flatMapLatest {
                generateFlowOfStrings(it)
            }.collect{
                delay(2000)
                println("collected: ---> $it")
            }
    }

}
Clone this wiki locally