MRSasko
12/07/2021, 7:44 AMfun fetchInfo(): Flow<State<SportInfo>> =
flow {
val result = memoryInfoResult
if (result != null) {
emit(result)
} else {
fetchSportInfo()
.onEach { result ->
when (result) {
is Data -> {
memoryInfoResult = result
emit(result)
}
is Error, is Loading -> {
emit(result)
}
}
}
}
}
Nick Allen
12/07/2021, 7:55 AMonEach
with collect
. onEach
is not a terminating operator (not one that actually runs the flow).Flow
is cold. So if you have 5 collectors, then they are all updating memoryInfoResult
. Usually for something with shared data, I prefer a SharedFlow
. Should be able to just tack .shareIn(someScope, SharingStarted.WhileSubscribed())
at the end which will run the flow only once for any number of subscribers at a time.MRSasko
12/07/2021, 11:37 AMonEach
with collect
. I also had to change the flow
builder to channelFlow
, and replace emit
with send
.
I only have one collector right now. But I might add more at some point.channelFlow
necessary in this example?Nick Allen
12/07/2021, 5:31 PMcollect
, channelFlow
is needed any time you are dealing with multiple coroutine contexts which takes extra overhead to deal with correctly. flow
is optimized for cases where you don't need that overhead.