Orhan Tozan
03/18/2020, 6:52 PMclass 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?Zach Klippenstein (he/him) [MOD]
03/18/2020, 7:03 PMBroadcastChannel
or ConflatedBroadcastChannel
and convert it into a Flow
using asFlow()
. Then you can offer
values to the channel and they will be emitted.magnumrocha
03/18/2020, 7:08 PMprivate val colorBroadcastChannel = ConflatedBroadcastChannel<Color>
val selectedColor: Flow<Color> = colorBroadcastChannel.asFlow()
fun onNewColorSelect(newColor: Color) {
colorBroadcastChannel.offer(color)
}
Zach Klippenstein (he/him) [MOD]
03/18/2020, 7:10 PMmagnumrocha
03/18/2020, 7:11 PMOrhan Tozan
03/18/2020, 7:11 PMselectedColor
as a Flow<Color>
instead of a ConflatedBroadcastChannel<Color>
?magnumrocha
03/18/2020, 7:13 PMOrhan Tozan
03/18/2020, 7:13 PMConflatedBroadcastChannel<T>
is also write-ablemagnumrocha
03/18/2020, 7:14 PMZach Klippenstein (he/him) [MOD]
03/18/2020, 7:17 PMFlow
immediately gives your consumers access to all the flow operators.magnumrocha
03/18/2020, 7:18 PMOrhan Tozan
03/18/2020, 7:19 PM.offer()
over .send()
?Zach Klippenstein (he/him) [MOD]
03/18/2020, 7:19 PMsend()
is a suspend function, so you can’t call it directly from onNewColorSelect()
ConflatedBroadcastChannel
, the effect is always the same (send
never suspends, offer
always returns true
)Orhan Tozan
03/18/2020, 7:34 PMFlow<T>
, but should not use the flow
operator? For example, if I want to initialize the selectedColor Flow with a suspending getRemoteColor()
function.magnumrocha
03/18/2020, 8:02 PMflow
creates a Flow
that completes (or close) when the it hits its finish like:
flow<MyObj> {
doOperation1()
doOperation2()
... // after this line this flow will close
}
Orhan Tozan
03/18/2020, 8:57 PM.map()
vs .transform()
.Zach Klippenstein (he/him) [MOD]
03/18/2020, 11:08 PMmap
is a special case of transform
, if you always want to emit exactly one downstream value for each upstream value:
fun <T, R> Flow<T>.map(
mapper: suspend (T) -> R
): Flow<R> = transform { emit(mapper(it)) }