How can I emit the result to the consumer from a d...
# coroutines
m
How can I emit the result to the consumer from a different function. When I try the following nothing happens?
Copy code
fun 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)
            }
          }
        }
      }
    }
n
Replace
onEach
with
collect
.
onEach
is not a terminating operator (not one that actually runs the flow).
👍 1
Also, this code is setup so if you have a cached result, you will never return anything else (updates are in an else).
And remember that
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.
m
thanx @Nick Allen. It helped to replace
onEach
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.
Why is the
channelFlow
necessary in this example?
n
not sure, I wouldn't expect it to be needed from
collect
,
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.