从 kotlin 流构建列表

时间:2021-07-23 12:50:42

标签: android kotlin kotlin-coroutines android-mvvm kotlin-flow

我正在尝试构建一个应用程序,该应用程序使用从数据层到视图的 kotlin 流程,但在处理诸如此类的简单问题时遇到了很多困难。

我正在从来自我的数据层的 StateFlow 收集整数值,并希望在我将其共享给我的视图模型并通过另一个 StateFlow 查看之前从中构建一个列表。

示例代码:

class MyDataSource {
    val inputFlow: StateFlow<Int> = TODO()
}

class MyService(
    dataSource: MyDataSource
) {
    private val intList: MutableList<Int> = ArrayList()

    private val _intFlow = MutableStateFlow<List<Int>>(listOf())
    val intFlow: StateFlow<List<Int>> = _intFlow

    init {
        GlobalScope.launch(Dispatchers.IO) {
            dataSource.inputFlow.collect {
                if (!intList.contains(it))
                    intList.add(it)
                
                _intFlow.emit(ArrayList(intList))
            }
        }
    }
}

难道没有更好的方法来做到这一点吗?就像我错过的流量运算符?这看起来特别难看,因为我每次都需要构建一个新的 ArrayList,否则即使 List 的内容改变了,流也不会发送新值,因为它仍然是同一个 List。

2 个答案:

答案 0 :(得分:1)

你可以做一些清理工作,但我认为流动不断增长的列表的安排过于具体,核心库中没有任何一体式解决方案。

  1. 你应该avoid using GlobalScope。这个服务类应该更合适地拥有自己的范围,以便您可以在需要时管理生命周期。

  2. 您的后备列表应该是一个集合,因为在添加对象之前,您实际上是通过检查对象是否在其中来将其用作性能不佳的集合。

  3. 使用链运算符和 stateIn 会更干净,而不是操作 MutableStateFlow 并且必须使用支持属性。

class MyService(
    dataSource: MyDataSource
) {
    private val intSet = mutableSetOf<Int>()
    private val scope = CoroutineScope(Dispatchers.Default)

    val intFlow = dataSource.inputFlow
        .map {
            intSet += it
            intSet.toList()
        }.stateIn(scope, SharingStarted.Eagerly, emptyList())
}

编辑:这是在每次迭代中避免设置到列表副本和新分配的未经测试的尝试:

class MyService(
    dataSource: MyDataSource
) {
    private val intSet = mutableSetOf<Int>()
    private var currentList = mutableListOf<Int>()
    private var previousList = mutableListOf<Int>()
    private var lastEmittedValue: Int? = null
    private val scope = CoroutineScope(Dispatchers.Default)

    val intFlow = dataSource.inputFlow
        .mapNotNull { newValue ->
            if (!intSet.add(newValue)) 
                return@mapNotNull null
            lastEmittedValue?.let {
                previousList += it
            } // both backing lists now identical
            lastEmittedValue = newValue
            previousList = currentList.also { currentList = previousList }
            // previousList is the one missing lastEmittedValue on next iteration:
            currentList += newValue
            currentList
        }.stateIn(scope, SharingStarted.Eagerly, emptyList())
}

答案 1 :(得分:0)

scan 能满足您的需求吗?

来自文档:

<块引用>

使用操作折叠给定的流,发出每个中间结果,包括初始值。 [...] 例如:

flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() 将产生 [], [1], [1, 2], [1, 2, 3]]

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/scan.html