0

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

enter image description here

Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127

1 Answers1

1

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

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • can you guide me how to add,prepend list value in mutableStateFlow? – Kotlin Learner Jan 13 '22 at 21:41
  • The way you're doing it is fine. You just can't do it in the same coroutine that is collecting it. Any code after a `collect` call will never be reached. If you want to collect a single value and then continue in the coroutine, you can use `first` instead of `collect`. – Tenfour04 Jan 13 '22 at 21:42
  • can you give me example please? – Kotlin Learner Jan 13 '22 at 21:50
  • Replace `collectLatest` with `first` or `first().let`, basically. But in an actual app you would not be emitting to a flow and collecting from it in the same coroutine. – Tenfour04 Jan 13 '22 at 21:53
  • Got it @Tenfour04 thanks a million. I am leaning basic because I need to implement this in my android application. But I don't understand why this is not working in my android application. Can you please guide me on this [issue](https://stackoverflow.com/q/70699636/11560810) – Kotlin Learner Jan 13 '22 at 21:58