Kotlin 协程:通道与流
Kotlin Coroutines: Channel vs Flow
我最近正在研究和阅读很多关于 Flow 和 Kotlin 协程的内容。但是我仍然对什么时候应该使用 Flow
什么时候应该使用 Channel
.
感到困惑
一开始看起来比较简单。处理热数据流? Channel
。冷的吗? Flows
。如果您需要从多个地方收听数据流,情况也是如此;如果是这样的话 Channel
是选择。还有很多例子和问题。
但最近 FlowChannels
引入了很多鼓励使用 Flow
的方法和 类,这有助于将 Channels
转换为 Flows
等等。随着每个 Kotlin 版本中出现所有这些新东西,我变得越来越困惑。所以问题是:
什么时候应该使用Channel,什么时候应该使用Flow?
对于迄今为止最好的工具是 Channel
的许多用例,Flow
已成为新的最佳工具。
作为具体示例,callbackFlow
现在是从第 3 方 API 的回调接收数据的最佳方法。这在 GUI 设置中特别有效。它将回调、通道和关联的接收协程耦合在同一个独立的 Flow
实例中。只有在收集流时才会注册回调。流程的取消会自动传播到关闭通道和注销回调。您只需提供一次回调注销代码即可。
您应该将 Channel
视为 Flow
在其实现中使用的低级原语。只有在您意识到 Flow
不符合您的要求后才考虑直接使用它。
我认为这里有一个很好的解释(Roman Elizarov) Cold flows, hot channels:
Channels are a great fit to model data sources that are intrinsically hot, data sources that exist without application’s requests for them: incoming network connections, event streams, etc.
Channels, just like futures, are synchronization primitives. You shall use a channel when you need to send data from one coroutine to another coroutine in the same or in a different process
But what if we don’t need either concurrency or synchronization, but need just non-blocking streams of data? We did not have a type for that until recently, so welcome Kotlin Flow type...
Unlike channels, flows do not inherently involve any concurrency. They are non-blocking, yet sequential. The goal of flows is to become for asynchronous data streams what suspending functions are for asynchronous operations — convenient, safe, easy to learn and easy to use.
我最近正在研究和阅读很多关于 Flow 和 Kotlin 协程的内容。但是我仍然对什么时候应该使用 Flow
什么时候应该使用 Channel
.
一开始看起来比较简单。处理热数据流? Channel
。冷的吗? Flows
。如果您需要从多个地方收听数据流,情况也是如此;如果是这样的话 Channel
是选择。还有很多例子和问题。
但最近 FlowChannels
引入了很多鼓励使用 Flow
的方法和 类,这有助于将 Channels
转换为 Flows
等等。随着每个 Kotlin 版本中出现所有这些新东西,我变得越来越困惑。所以问题是:
什么时候应该使用Channel,什么时候应该使用Flow?
对于迄今为止最好的工具是 Channel
的许多用例,Flow
已成为新的最佳工具。
作为具体示例,callbackFlow
现在是从第 3 方 API 的回调接收数据的最佳方法。这在 GUI 设置中特别有效。它将回调、通道和关联的接收协程耦合在同一个独立的 Flow
实例中。只有在收集流时才会注册回调。流程的取消会自动传播到关闭通道和注销回调。您只需提供一次回调注销代码即可。
您应该将 Channel
视为 Flow
在其实现中使用的低级原语。只有在您意识到 Flow
不符合您的要求后才考虑直接使用它。
我认为这里有一个很好的解释(Roman Elizarov) Cold flows, hot channels:
Channels are a great fit to model data sources that are intrinsically hot, data sources that exist without application’s requests for them: incoming network connections, event streams, etc. Channels, just like futures, are synchronization primitives. You shall use a channel when you need to send data from one coroutine to another coroutine in the same or in a different process
But what if we don’t need either concurrency or synchronization, but need just non-blocking streams of data? We did not have a type for that until recently, so welcome Kotlin Flow type...
Unlike channels, flows do not inherently involve any concurrency. They are non-blocking, yet sequential. The goal of flows is to become for asynchronous data streams what suspending functions are for asynchronous operations — convenient, safe, easy to learn and easy to use.