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

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

或者, case 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的设置器来通知订阅者:

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

Kotlin相关问答推荐

直接从SON解析NonEmptyList

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

插入/更新/upsert时不发出房间流

我可以更改方法中泛型类的类型参数边界吗?

Kotlin Poet 的导入不明确

列表在 android WebView 中没有正确迭代

如何在 Jetpack Compose 中启动和停止动画

kotest 更改环境变量

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

嵌套数组 indexOf()

SpringBoot 2.5.0 对于 Jackson Kotlin 类的支持,请在类路径中添加com.fasterxml.jackson.module: jackson-module-kotlin

在粘贴时将 java 转换为 kotlin

Kotlin默认使用哪种排序?

Kotlin not nullable值可以为null吗?

项目未与 Gradle 链接

Kotlin中的属性(properties)和参数(parameters)有什么区别?

如何启用spring security kotlin DSL?

使用 kotlin 每 3 位数添加逗号或点

访问Kotlin中的属性委托

如何在伴随对象中使用泛型