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

  • Learning Concurrency in Kotlin
  • Miguel Angel Castiblanco Torres
  • 261字
  • 2021-08-05 10:46:50

A synchronous function wrapped in an asynchronous caller

The first approach is quite simple. We can create a loadNews() function that directly invokes fetchRssHeadlines() and displays its results in the same way we did before:

private fun loadNews(){
val headlines = fetchRssHeadlines()
val newsCount = findViewById<TextView>(R.id.newsCount)
launch(UI) {
newsCount.text = "Found ${headlines.size} News"
}
}

Notice that this function is synchronous, and will call fetchRssHeadlines() in the same thread that it's called. Consider this code, for example:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadNews()
}

Doing this will result in a NetworkOnMainThreadException being thrown. Since loadNews() uses the same thread it's being called on, the request to fetch the feed will happen in the UI thread. To fix this, we can then wrap the call to loadNews() in a launch() block like we did before, using the dispatcher that was created for the service request. The code would be almost the same:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launch (dispatcher) {
loadNews()
}
}

This code is quite explicit, indicating that there is some code being executed asynchronously, which is a great practice. It's also quite flexible, because if the caller of loadNews() is already in a background thread, it can fetch the news in the same background thread, without having to use a launch() or async() builder.

The disadvantage of this approach is that if we have many places calling loadNews() from the UI thread, we would have many similar blocks of launch(dispatcher) {...} spread in the code, which can make the code less readable.

主站蜘蛛池模板: 肃宁县| 阳曲县| 凌云县| 芦溪县| 雅安市| 乌兰县| 镇赉县| 阳春市| 清河县| 霞浦县| 曲阜市| 景洪市| 和平县| 蓬溪县| 桂阳县| 平果县| 芦山县| 岚皋县| 翁源县| 新邵县| 玉环县| 博野县| 甘孜县| 泌阳县| 宜城市| 洮南市| 靖州| 都匀市| 饶阳县| 瑞丽市| 寻乌县| 博乐市| 平原县| 宜川县| 建平县| 东宁县| 阳山县| 高要市| 华阴市| 静宁县| 清丰县|