Given the following viewmodel: ```class ViewModel ...
# coroutines
o
Given the following viewmodel:
Copy code
class ViewModel {
    val selectedColor: Flow<Color> = ...
    fun onNewColorSelect(newColor: Color) {
        ...
    }
}
How can the
onNewColorSelect
method update the
selectedColor
flow? With Android, you would use
MutableLiveData
. How would you solve this problem with Flow?
z
Copy code
val selectedColorChannel = ConflatedBroadcastChannel<Color>(..)
val selectedColor: Flow<Color> = selectedColorChannel.asFlow()
o
.
z
then
selectedColorChannel.offer(color)
(you just need to back your
Flow<T>
with a
ConflatedBroadcastChannel<T>
, at least until
StateFlow
is implemented https://github.com/Kotlin/kotlinx.coroutines/issues/1082
remember,
Channel<T>
is the synchronization primitive that allows you to communicate between coroutines
o
I read alot that Flow is encouraged over Channels, since Flow seems to use channel under the hood?
And why would one use ConflatedBroadcastChannel when Flow has the .conflate() method
z
it’s just confusing because flow and channels serve two different purposes, though both seem wrappers around asynchronous emissions of
T
Channels are a non-blocking queue of items. It’s a literal data structure
Passing around a
Channel<T>
is like passing around a List. It’s not an abstraction over observing values of
T
o
And passing around a
ConflatedBroadcastChannel<T>
is like passing around the latest value of
T
?.
👍 1
z
Flows are “cold” meaning they have some abstraction around subscribing to them. If you hook up a
Flow<T>
to a
ConflatedBroadcastChannel<T>
, this abstraction allows you to register a call to
.openSubscrition()
, and when the Flow is closed, close the
ReceiveChannel<T>
you get from that
.openSubscription()
call
correct.
ConflatedBroadcastChannel<T>
is literally a reactive version of a regular variable like
var state: T
👍 1
o
Thanks Zak, really helpful. The analogy helps alot.
What would be the difference between
Channel<T>
and
BroadcastChannel
?
Also, if
ConflatedBroadcastChannel<T>
is literally a reactive version of a regular variable like
var state: T
Does that mean people should generally use
ConflatedBroadcastChannel<T>
over
Flow<T>
with ViewModels?
1
z
Does that mean people should generally use ConflatedBroadcastChannel<T> over Flow<T> with ViewModels? (edited)
You actually use both