Supporting a list of feeds

Let's go back to our Android Studio project and create an immutable list to hold the feeds that we will fetch. For now, three feeds will be enough:

class MainActivity : AppCompatActivity() {

val feeds = listOf(
"https://www.npr.org/rss/rss.php?id=1001",
"http://rss.cnn.com/rss/cnn_topstories.rss",
"http://feeds.foxnews.com/foxnews/politics?format=xml"
)
...
}

Now we have a list of feeds that contain the URLs of NPR, CNN, and Fox News, let's update the fetchRssHeadlines() function to have it adjust to our goal:

private fun asyncFetchHeadlines(feed: String,
dispatcher: CoroutineDispatcher) = async(dispatcher) {
val builder = factory.newDocumentBuilder()
val xml = builder.parse(feed)
val news = xml.getElementsByTagName("channel").item(0)

(0 until news.childNodes.length)
.map { news.childNodes.item(it) }
.filter { Node.ELEMENT_NODE == it.nodeType }
.map { it as Element }
.filter { "item" == it.tagName }
.map {
it.getElementsByTagName("title").item(0).textContent
}
}

Note that instead of having a single feed, now our function takes a feed argument that is the URL that it'll use to fetch the news. This will allow us to fetch headlines from more than one feed. Additionally, the signature of the function has changed so that it's now an asynchronous function that takes the dispatcher to be used as an argument.

The name of the function has been updated to include async, as good practice suggests. The name has also been shortened for better readability.
..................Content has been hidden....................

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