Hi everyone, I'm trying to use MutableStateFlow, e...
# coroutines
m
Hi everyone, I'm trying to use MutableStateFlow, encapsulating a List of an object, but when I update it with some new value, the collectLatest{} method doesn't work, can you help me please? This method doesn't update the value
Copy code
@ExperimentalCoroutinesApi
fun deleteSelected() {
    val value = dataPoints.value
    value.removeAll { it.selected }
    dataPoints.value = ArrayList(value)
}
b
because when you assign new list to it (dataPoints.value = ....) it checks objects for equality, and they're equal because value is mutable
I suggest switching to immutable List<> and use filter instead of removeAll:
Copy code
dataPoints.value = dataPoints.value.filter { !it.selected }
If you strongly prefer to use ArrayList directly, you need to write:
Copy code
val value = ArrayList(dataPoints.value)
value.removeAll { it.selected }
dataPoints.value = value
m
@bezrukov that worked, thank you.
👍 1
@bezrukov
Copy code
fun sweepAll() {
    val value = mutableListOf<DataPoint>()
    value.addAll(dataPoints.value)
    value.forEach {
        it.x = null
        it.y = null
    }
    dataPoints.value = value
}
I have this function and the value again is not changing, can you please tell me why is that?
b
because your points are mutable
stateflow works only with immutable data. To receive an update, value needs to be changed when you set
dataPoints.value = value
. But you made
it.x = null
on original datapoint, so it was changed in both lists
if you want to transfer mutable data over StateFlow you need to write some wrapper that will have a changed property. Something like:
data class Wrapper(val version: Int, data: List<DataPoints>)
and on each update you need to copy this wrapper with increased
version
. but it's hacky and better to use immutable data.
113 Views