12

In the past, I was using LocalBroadcastManager and EventBus in my chat and taxicab applications which are now either deprecated or not recommended using them.

I intend to replace them with new data structures like mutablesharedflow or channel, i want to know which one is better matched with my case? or maybe another data structure?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
sok sok
  • 215
  • 4
  • 9

2 Answers2

17

From Roman Elizarov, Channels were added as an inter-coroutine communication primitive.

You cannot use channels to distribute events or state updates in a way that allows multiple subscribers to independently receive and react upon them.

So they introduced Flow. But Flow is a cold observable, where every subscriber gets their own data (independent from other subscribers). With SharedFlow you get a hot observable that emits independently of having any subscriber(s).

You could do the same with ConflatedBroadcastChannel. But JetBrains recommend to use Flow in favor of Channels because of their simpler API.

So if you want to migrate to Coroutines and you need a hot observable multiple subscribers can listen to, you should go with SharedFlow.

ChristianB
  • 2,452
  • 2
  • 10
  • 22
  • I really appreciate your comment, it is very helpful. i actually forgot to take MutableStateFlow into account, i'd like to know your opinion between StateFlow and SharedFlow in this scenario? – sok sok Dec 26 '20 at 17:54
  • 1
    You are welcome. A StateFlow extends the SharedFlow. It is the same, but with a cached `value` property. So you can get it's latest state at any time, even outside the flow observation like `yourStateFlow.value`. So If you not just want to notify, but also allow others to ask the flows current state/value you should use `StateFlow`. – ChristianB Dec 26 '20 at 18:00
  • 1
    Note: `ConflatedBroadcastChannel` is obsolete since 1.5.0. It will be deprecated with warning in 1.6.0 and with error in 1.7.0. It is replaced with `StateFlow`. So from now on, should avoid using it. If you want to have multiple subscibers to subscribe to the same event use `SharedFlow`. – Arst Dec 21 '22 at 23:27
-7

Both are good for listening one time events. Everything depends in your use cases.

SharedFlow known as hot flow ->

  1. Emit events even if no observer is listening to it
  2. If no observer is listening to it, you loose these events

Channels known as cold flow

  1. Does not emit events when no observer is not listening to it. It works like a BlockingQueue.
  2. When you start to collect, it collects all data which were sent.