gpt4 book ai didi

android - 如何在 Kotlin 中合并流和 channel ?

转载 作者:行者123 更新时间:2023-12-02 12:50:46 24 4
gpt4 key购买 nike

我需要创建一个 API,它应该是流,它收集事件。问题是这些事件可能来自一个 channel (我需要一个用于 PublishSubject 的模拟)和一个流(它执行网络请求)。

我也不确定这是否是最好的解决方案,所以让我知道我是否可以做得更好。

我在做什么:

我的 API:

override val statusFlow = trackStatus()

private fun trackStatus(): Flow<State> = flow { ... }

private val deviceChannel = Channel<State>(CONFLATED)

所以 statusFlow 应该返回一个流,我可以从中接收来自流和 channel 的数据。

我试图通过consumeAsflow将 channel 转换为流,但它不起作用。

我看到一个解决方案
private fun trackStatus(): Flow<State> = flowOf(channel.toFlow(), flow).flattenMerge()

正确的方法是什么?

最佳答案

private fun trackStatus() = merge(deviceChannel.recieveAsFlow(), trackStatus)
merge() 的定义来自协程库是
/**
* Merges the given flows into a single flow without preserving an order of elements.
* All flows are merged concurrently, without limit on the number of simultaneously collected flows.
*
* ### Operator fusion
*
* Applications of [flowOn], [buffer], [produceIn], and [broadcastIn] _after_ this operator are fused with
* its concurrent merging so that only one properly configured channel is used for execution of merging logic.
*/
@ExperimentalCoroutinesApi
public fun <T> merge(vararg flows: Flow<T>): Flow<T> = flows.asIterable().merge()

关于android - 如何在 Kotlin 中合并流和 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62130107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com