如何将Flow>>>转换为Flow>>?

huangapple go评论80阅读模式
英文:

How to transform Flow<List<Flow<List<T>>>> to Flow<List<List<T>>>?

问题

仅期望一个单一Flow包装在整个内容之外,而不是在内部有更多的Flow(内部Flow的内容更改应该只是简单地更改外部Flow的内容)。

英文:

Consider the following,

  1. val tabs: MutableStateFlow&lt;List&lt;Path&gt;&gt; = getFlowPaths() // user defined
  2. //A function Path.contents(glob: String = &quot;*&quot;): Flow&lt;List&lt;Path&gt;&gt;
  3. val tabsFlow: Flow&lt;List&lt;Flow&lt;List&lt;Path&gt;&gt;&gt;&gt; = tabs.transformLatest {
  4. emit(it.map { path -&gt;
  5. path.contents()
  6. })
  7. }
  8. //But I want tabsFlow to be Flow&lt;List&lt;List&lt;Path&gt;&gt;&gt;, 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

以下是翻译好的代码部分:

  1. 一种可能的方法是
  2. val tabsFlow: Flow<List<List<Path>>> = tabs.flatMapLatest { paths ->
  3. combine(paths.map { path ->
  4. path.contents()
  5. }) { it.toList() }
  6. }
  7. val contentsFlows: List<Flow<List<Path>>> = tabs.value.map { path ->
  8. path.contents()
  9. }
  10. val res: Flow<List<List<Path>>> = combine(contentsFlows) { contents ->
  11. contents.toList()
  12. }
英文:

One possible way to do this:

  1. val tabsFlow: Flow&lt;List&lt;List&lt;Path&gt;&gt;&gt; = tabs.flatMapLatest { paths -&gt;
  2. combine(paths.map { path -&gt;
  3. path.contents()
  4. }) { it.toList() }
  5. }

or

  1. val contentsFlows: List&lt;Flow&lt;List&lt;Path&gt;&gt;&gt; = tabs.value.map { path -&gt;
  2. path.contents()
  3. }
  4. val res: Flow&lt;List&lt;List&lt;Path&gt;&gt;&gt; = combine(contentsFlows) { contents -&gt;
  5. contents.toList()
  6. }

huangapple
  • 本文由 发表于 2023年3月4日 02:09:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定