- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 307字
- 2021-08-05 10:46:48
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.
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()
}
- C++案例趣學(xué)
- Designing Machine Learning Systems with Python
- HTML5 移動(dòng)Web開發(fā)從入門到精通(微課精編版)
- Amazon S3 Cookbook
- IBM Cognos Business Intelligence 10.1 Dashboarding cookbook
- 寫給程序員的Python教程
- C編程技巧:117個(gè)問題解決方案示例
- Android Studio開發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到App上線 (移動(dòng)開發(fā)叢書)
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛上編程(全彩)
- Responsive Web Design with jQuery
- 現(xiàn)代C++語言核心特性解析
- Python人工智能項(xiàng)目實(shí)戰(zhàn)
- ASP.NET jQuery Cookbook(Second Edition)
- Go語言編程之旅:一起用Go做項(xiàng)目
- Effective Python:編寫高質(zhì)量Python代碼的90個(gè)有效方法(原書第2版)