我有这些代码,我想让它变得更优化
我想我可以使用kotlin- flow的flatMapMerge,但我不认为应该如何将我的代码转换为flow
val quiries = listof("s","b","s","g","d","r","t")
quiries.map { query ->
viewModelScope.launch {
val results = fetchColumns(query)
resultMutableData.postValue(results)
}
}和fetchColumns()都是挂起的函数,我想也许我需要有查询流?使用flatMapMerge()的方法是什么?
发布于 2019-09-13 05:04:22
试着使用这样的东西:
listOf("s","b","s","g","d","r","t").asFlow()
.map { fetchColumns(it) }
.onEach { resultMutableData.postValue(it) }
.launchIn(viewModelScope)因为您不需要切换到另一个流,所以不需要任何flatMap*函数,只需要map就足够了。此外,map参数已经声明为suspend,因此不会阻塞线程。但是map运算符被设计为按顺序处理数据,因此这些转换不会并行运行。要实现并行处理,可以使用使用flatMapMerge的解决方法:
listOf("s","b","s","g","d","r","t").asFlow()
.onEach { println("onEach: $it") }
.flatMapMerge {
flow {
emit(fetchColumns(it))
}
}
.onEach { resultMutableData.postValue(it)) }
.launchIn(viewModelScope)https://stackoverflow.com/questions/57857304
复制相似问题