当过滤器需要更改时重新运行 StateFlow?

Rerun StateFlow When Filter Needs to Change?

我有一个 StateFlow 包含一个简单的字符串列表。我希望能够过滤该字符串列表。每当过滤器更新时,我想向 StateFlow 推出新的更新。

class ResultsViewModel(
    private val api: API
) : ViewModel() {

  var filter: String = ""
  val results: StateFlow<List<String>> = api.resultFlow()
        .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
}

map 粘贴到 api.resultFlow() 上很容易:

  val results: StateFlow<List<String>> = api.resultFlow()
        .map { result ->
            val filtered = mutableListOf<String>()
            for (r in result) {
                if (r.contains(filter)) {
                   filtered.add(r)
                }
            }
            filtered
        }
        .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())

但是如何让流程在 filter 发生变化时实际发出更新?现在,这仅适用于 filter 的初始值设置为什么。

您可以让过滤器更新与另一个 StateFlow 相结合的另一个 StateFlow。顺便说一下,filter 函数比手动创建另一个列表并迭代以获得结果更容易使用。

class ResultsViewModel(
    private val api: API
) : ViewModel() {

  private val filterFlow = MutableStateFlow("")

  var filter: String
    get() = filterFlow.value
    set(value) {
        filterFlow.value = value
    }

  val results: StateFlow<List<String>> = 
    api.resultFlow()
      .combine(filterFlow) { list, filter ->
          list.filter { it.contains(filter) }
      }
      .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
}