英文:
How to transform Flow<List<Flow<List<T>>>> to Flow<List<List<T>>>?
问题
仅期望一个单一Flow包装在整个内容之外,而不是在内部有更多的Flow(内部Flow的内容更改应该只是简单地更改外部Flow的内容)。
英文:
Consider the following,
val tabs: MutableStateFlow<List<Path>> = getFlowPaths() // user defined
//A function Path.contents(glob: String = "*"): Flow<List<Path>>
val tabsFlow: Flow<List<Flow<List<Path>>>> = tabs.transformLatest {
emit(it.map { path ->
path.contents()
})
}
//But I want tabsFlow to be Flow<List<List<Path>>>, is it possible to get it?
What I'm expecting,
Only a single Flow wrapped outside the whole thing rather than having more flow inside (change in content of inside flow should just simply change the content of outside flow).
答案1
得分: 0
以下是翻译好的代码部分:
一种可能的方法是:
val tabsFlow: Flow<List<List<Path>>> = tabs.flatMapLatest { paths ->
combine(paths.map { path ->
path.contents()
}) { it.toList() }
}
或
val contentsFlows: List<Flow<List<Path>>> = tabs.value.map { path ->
path.contents()
}
val res: Flow<List<List<Path>>> = combine(contentsFlows) { contents ->
contents.toList()
}
英文:
One possible way to do this:
val tabsFlow: Flow<List<List<Path>>> = tabs.flatMapLatest { paths ->
combine(paths.map { path ->
path.contents()
}) { it.toList() }
}
or
val contentsFlows: List<Flow<List<Path>>> = tabs.value.map { path ->
path.contents()
}
val res: Flow<List<List<Path>>> = combine(contentsFlows) { contents ->
contents.toList()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论