Merging the responses

The current implementation of asyncLoadNews() will wait for each of the requests to end. But since each of them returns a list of headlines, we want to join all their results into a single list containing all of them. For this, we can flat map the content of each deferred:

val headlines = requests.flatMap {
it.getCompleted()
}

So now we have a headlines variable that contains all the headlines fetched concurrently from the three feeds. At this point, asyncLoadNews() will have two sections. The first one is to fetch and organize the data:

private fun asyncLoadNews() = launch {
val requests = mutableListOf<Deferred<List<String>>>()

feeds.mapTo(requests) {
asyncFetchHeadlines(it, dispatcher)
}

requests.forEach {
it.await()
}

val headlines = requests.flatMap {
it.getCompleted()
}
...

}

The second half, just below the first one, displays the amount of headlines on the UI:

val newsCount = findViewById<TextView>(R.id.newsCount)

launch(UI) {
newsCount.text = "Found ${headlines.size} News"
}

Let's update the second section so that the message that we print also displays the amount of feeds that were fetched:

val newsCount = findViewById<TextView>(R.id.newsCount)

launch(UI) {
newsCount.text = "Found ${headlines.size} News " +
"in ${requests.size} feeds"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.48.204