I read multiple articles trying to find an answer explaining difference.
- Quoting the answer here : channel or mutablesharedflow , which one is a better replacement for deprecated localbroadcastmanager
From Roman Elizarov, Channels were added as an inter-coroutine communication primitive.
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.
- https://betterprogramming.pub/stop-calling-kotlin-flows-hot-and-cold-48e87708d863
-
When you want to encapsulate your value-producing code so that consumers don’t have to worry about when it starts, stops or fails, use a flow.
-
when you want to pass values from one coroutine to another, use a channel.
Can you elaborate on those examples? I kinda do not understand when you want to encapsulate your value-producing code so that consumers don’t have to worry about when it starts, stops or fails, use a flow.
Also in the project I work in we are using Channel in MVI View Model implementation.
private val uiEvents = Channel<UiEvent>
(Channel.UNLIMITED)viewModelScope.launch(dispatcher) {
uiEvents.consumeAsFlow().collect { uiEvent ->
fun push(event: UiEvent) {
uiEvents.trySend(event)
}
Is that correct use case for Channel?
What meaning is behind “when you want to pass values from one coroutine to another, use a channel”
Can I understand this that way that In one place I for eg send event of type Unit to display a toast in a fragment then? Suppose only one fragment collects this event. I think this could work with Channel and therefore I am confused.