官术网_书友最值得收藏!

Creating a coroutine to call a service

Now it's a good time to add a call to a service. To start with something simple, we will use Java's DocumentBuilder to call an RSS feed for us. First, we will add a variable to hold the DocumentBuilderFactory below where we put the dispatcher:

private val dispatcher = newSingleThreadContext(name = "ServiceCall")
private val factory = DocumentBuilderFactory.newInstance()

The second step is to create a function that will do the actual call:

private fun fetchRssHeadlines(): List<String> {
val builder = factory.newDocumentBuilder()
val xml = builder.parse("https://www.npr.org/rss/rss.php?id=1001")
return emptyList()
}

Notice how the function is, for now, returning an empty list of strings after calling the feed. The idea is to implement this function so that it returns the headlines of the given feed. But, first let's call this function as part of the coroutine defined previously:

launch(dispatcher) {
fetchRssHeadlines()
}

Now, the fetching of the headlines will happen in the thread of dispatcher. The next step is to actually read the body of the response and return the headlines. For this example, we are going to parse the XML by hand – as opposed to using some library to do the parsing:

private fun fetchRssHeadlines(): List<String> {
val builder = factory.newDocumentBuilder()
val xml = builder.parse("https://www.npr.org/rss/rss.php?id=1001")
val news = xml.getElementsByTagName("channel").item(0)
return (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
}
}

This code is simply going through all elements in the XML and filtering out everything but the title of each article in the feed.

Both Element and Node are from the package org.w3c.dom.

Now that the function is actually returning the information, we can receive it in preparation to display it on the user interface:

launch(dispatcher) {
val headlines = fetchRssHeadlines()
}
主站蜘蛛池模板: 楚雄市| 海伦市| 乌拉特前旗| 甘德县| 绵阳市| 当涂县| 曲阳县| 大渡口区| 淮南市| 北流市| 南丰县| 福贡县| 宁化县| 阿克苏市| 金塔县| 望江县| 建阳市| 汕尾市| 亚东县| 海城市| 海门市| 仙桃市| 梅州市| 莱阳市| 临城县| 西畴县| 边坝县| 正定县| 武川县| 新巴尔虎右旗| 十堰市| 皋兰县| 宁陕县| 亳州市| 南陵县| 清苑县| 巴中市| 焦作市| 两当县| 建瓯市| 磴口县|