Question Details

No question body available.

Tags

kotlin kotlin-flow

Answers (2)

Accepted Answer Available
Accepted Answer
November 30, 2025 Score: 2 Rep: 21,496 Quality: High Completeness: 60%

You should never use mutable content in a StateFlow, that won't register as a new value and won't notify the collectors of the change. Instead, use only unmodifyable List:

val list = MutableStateFlow(
    listOf(Pair(1, 1), Pair(1, 2))
)

(Please also note that this variable should be declared as val, not as var, because you will never want to assign a new MutableStateFlow to the list.)

With this you cannot use removeLastOrNull() anymore because that would modify the list. Instead you want to create a new list with all the elements except the last. You can use dropLast() for that, but if you need the old value of a MutableStateFlow to calculate the new value, you should use the update function instead of the value property to make the operation thread-safe:

list.update { it.dropLast(1) }

If you need the removed element for further processing you can retrieve it with it.lastOrNull() before dropping it.

November 29, 2025 Score: 2 Rep: 94,853 Quality: Low Completeness: 20%

The way Flows work is that they call all of the observers when a new value is emitted on it. When you put a mutable value inside the flow and mutate that value (like by calling remove), no new value is emitted on the Flow. Which means the observers will not be informed that the value changed. You need to emit a new value on it. And no, calling remove then re-emitting the same list will not work, because StateFlows do not emit if the value is unchanged.

You instead want to create a new list without the last value and then emit that value on the flow. That will properly notify all observers.