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.
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)
}
}
>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.".
