如何从var列表或可变列表中获取列表流



我想要一个在列表更新/更改时发出Flow<List<T>>的流。

案例1:

var l = listOf(1, 2, 3, 5)
val listFlowOfInt : Flow<List<Int>> = // A flow which will notify All subscribers (emit value) when l is re-assigned,
//say l= listOf(6,7,8), elsewhere in the code.

或者,情况2:

val l = mutableListOf(1, 2, 3, 5)
val listFlowOfInt : Flow<List<Int>> = // A flow which will notify All subscribers (emit value) when l is changed,
//say l.add(6), elsewhere in the code.

对于第一种情况,可以使用变量lMutableStateFlow的setter来通知订阅者:

val listFlowOfInt = MutableStateFlow<List<Int>>(emptyList())
var l: List<Int> = listOf(1, 2, 3, 5)
set(value) {
field = value
listFlowOfInt.value = value
}

对于第二种情况,您可以应用第一种解决方案,例如:

fun addValueToList(value: Int) {
// reasigning a list to `l`, the setter will be called.
l = l.toMutableList().apply { 
add(value)
}
}

最新更新