Hello :wave: Playing around with `Channel` based p...
# coroutines
d
Hello 👋 Playing around with
Channel
based pipelines and was wondering whether you have any suggestions to make it better. NOTE: for this exercise want to stick to channels only Consider following basic example - fetch list of items and for each one of them fetch additional information (details + reviews) that will be used to final result
Copy code
val result = mutableListOf()

val summaries = retrieveSummaries()
for (summary in summaries) {
   val details = retrieveDetails(summary.id)
   val reviews = retrieveReviews(summary.id)

   result.add(buildResult(summary, details, reviews)
}

return result
I could easily parallelize the above by doing something like
Copy code
summaries.map { summary -> 
  async {
    val details = async { retrieveDetails(summary.id) }
    val reviews = async { retrieveReviews(summary.id) }
    
    buildResult(summary, details.await(), reviews.await())
  }
}
Currently trying to figure out what would be the "best" way to achieve the same using
Channel
. "Simplest" would be to do a sequence of channels
Copy code
val summaries: ReceiveChannel<Summary> = summariesChannel()
val detailsAndSummaries: ReceiveChannel<Pair<Summary, Detail>> = detailsAndSummariesChannel(summaries)
val result: ReceiveChannel<Result> = resultChannel(detailsAndSummaries)
Looks like
BroadcastChannel
is marked obsolete but I guess logically it would make sense to broadcast summaries and then send both details and reviews from separate channels but I am unsure how to read from multiple channels at once (i.e.
buildResult
would need results from 3 channels). Any ideas/suggestions?
d
You can read from multiple channels using
select
and
channel.onReceive
.
👍 1
d
looks like
select
is able to pick first available element from X channels -> my use case in the above is that I need to consume messages from 3 channels to create a single result type
i.e. something like RX
zip
operator (which is marked as deprecated on channels)
j
why stick to channels specifically? shared flows in latest deprecate broadcast channels
message has been deleted
d
Its an exercise - got another one using flows as well