Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end / close a MutableSharedFlow?

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).

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).

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)

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

like image 750
Joffrey Avatar asked Oct 15 '20 13:10

Joffrey


People also ask

What is MutableSharedFlow?

MutableSharedFlow See the SharedFlow documentation for details on shared flows. MutableSharedFlow is a SharedFlow that also provides the abilities to emit a value, to tryEmit without suspension if possible, to track the subscriptionCount, and to resetReplayCache.

What is the difference between SharedFlow and StateFlow?

The main difference between a SharedFlow and a StateFlow is that a StateFlow takes a default value through the constructor and emits it immediately when someone starts collecting, while a SharedFlow takes no value and emits nothing by default.


1 Answers

The SharedFlow documentation describes what you need:

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 cannot be closed like BroadcastChannel and can never represent a failure. All errors and completion signals should be explicitly materialized if needed.

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.

like image 177
Kiskae Avatar answered Sep 23 '22 09:09

Kiskae