Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add, prepend and append value in MutableStateFlow in Kotlin

Hey I am new in Kotlin Flow. I am using MutableStateFlow to add value, append value, prepend value in flow.

1. I am trying to use println() after collectLatest it’s not printing anything. Can someone explain me why this is not working.

2. Can someone guide me how to add,append and prepend list in flow.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example

Append

my flow list value is [1, 2, 3, 4, 5] and want to add [6, 7, 8, 9, 10].

Output will be

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Prepend

The same list of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] after append. I want to do prepend in the list and the value is [-5, -4, -3, -2, -1].

Output will be

[-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I am trying but I don’t understand why this function is not working.

Main.kt

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest

suspend fun main(args: Array<String>) {
    val flow = MutableStateFlow<List<Int>>(emptyList())
    val updateList = listOf<Int>(-5, -4, -3, -2, -1)

    for (i in 1..10) {
        flow.value += i
    }

    flow.collectLatest {
        println(it)
    }

    println("After Update")
    flow.value = flow.value + updateList

    flow.collectLatest {
        println(it)
    }
}

enter image description here

>Solution :

A SharedFlow or StateFlow has no end unless it’s cancelled. Calling collect or collectLatest on it is sort of like creating a while(true) loop. It will never finish iterating because it’s always possible it will have another value emitted.

In the documentation you can read about it in the section that starts with"Shared flow never completes.".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading