如何结束/关闭MutableSharedFlow? [英] How to end / close a MutableSharedFlow?

查看:379
本文介绍了如何结束/关闭MutableSharedFlow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SharedFlow 刚在协程1.4.0-M1中引入,它意在替换所有 BroadcastChannel 实现(如

SharedFlow has just been introduced in coroutines 1.4.0-M1, and it is meant to replace all BroadcastChannel implementations (as stated in the design issue decription).

我有一个用例,其中我使用 BroadcastChannel 表示传入的Web套接字帧,以便多个侦听器可以订阅"消息.到框架.我移到 SharedFlow 时遇到的问题是我无法结束"消息.当我收到关闭帧或上游错误(我想通知所有订阅者该流已结束)时,该流将结束.

I have a use case where I use a BroadcastChannel to represent incoming web socket frames, so that multiple listeners can "subscribe" to the frames. The problem I have when I move to a SharedFlow is that I can't "end" the flow when I receive a close frame, or an upstream error (which I would like to do to inform all subscribers that the flow is over).

当我想有效地关闭"网站时,如何使所有订阅终止. SharedFlow ?有没有办法分辨普通闭包与异常闭包之间的区别?(如渠道)

How can I make all subscriptions terminate when I want to effectively "close" the SharedFlow? Is there a way to tell the difference between normal closure and closure with exception? (like channels)

如果 MutableSharedFlow 不允许将流的末尾传达给订户,那么如果 BroadcastChannel 被弃用/删除,该怎么办?

If MutableSharedFlow doesn't allow to convey the end of the flow to subscribers, what is the alternative if BroadcastChannel gets deprecated/removed?

推荐答案

The SharedFlow documentation describes what you need:

请注意,大多数终端运算符(例如Flow.toList)在应用于共享流时也不会完成,但是可以在共享流上使用流截断运算符(例如Flow.take和Flow.takeWhile)将其转换为完成操作一个.

Note that most terminal operators like Flow.toList would also not complete, when applied to a shared flow, but flow-truncating operators like Flow.take and Flow.takeWhile can be used on a shared flow to turn it into a completing one.

SharedFlow不能像BroadcastChannel一样关闭,永远不能代表失败.如果需要,应明确实现所有错误和完成信号.

SharedFlow cannot be closed like BroadcastChannel and can never represent a failure. All errors and completion signals should be explicitly materialized if needed.

基本上,您将需要引入一个可以从共享流中发出的特殊对象,以指示该流已结束,在消费者端使用 takeWhile 可以使它们一直发出,直到该特殊对象被释放为止.收到.

Basically you will need to introduce a special object that you can emit from the shared flow to indicate that the flow has ended, using takeWhile at the consumer end can make them emit until that special object is received.

这篇关于如何结束/关闭MutableSharedFlow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆