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

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

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

问题

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

英文:

Consider the following,

val tabs: MutableStateFlow&lt;List&lt;Path&gt;&gt; = getFlowPaths() // user defined

//A function Path.contents(glob: String = &quot;*&quot;): Flow&lt;List&lt;Path&gt;&gt;

val tabsFlow: Flow&lt;List&lt;Flow&lt;List&lt;Path&gt;&gt;&gt;&gt; = tabs.transformLatest {
        emit(it.map { path -&gt;
            path.contents()
        })
    }
//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

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

一种可能的方法是

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&lt;List&lt;List&lt;Path&gt;&gt;&gt; = tabs.flatMapLatest { paths -&gt;
        combine(paths.map { path -&gt;
            path.contents()
        }) { it.toList() }
    }

or

    val contentsFlows: List&lt;Flow&lt;List&lt;Path&gt;&gt;&gt; = tabs.value.map { path -&gt;
        path.contents()
    }

    val res: Flow&lt;List&lt;List&lt;Path&gt;&gt;&gt; = combine(contentsFlows) { contents -&gt;
        contents.toList()
    }

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:

确定