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

An asynchronous function with a predefined dispatcher

This brings us to the second option. We can write a function, asyncLoadNews(), that will contain the launch() inside it and return the resulting Job. This function can be called without a launch() block regardless of the thread; and by returning the Job, it's possible for the caller to cancel it:

private fun asyncLoadNews() = launch(dispatcher) {
val headlines = fetchRssHeadlines()
val newsCount = findViewById<TextView>(R.id.newsCount)
launch(UI) {
newsCount.text = "Found ${headlines.size} News"
}
}
By stipulating the signature of a function as fun asyncDo() = launch  {...}, not only are we making the whole function run inside a coroutine but we are also having it return the Job created for the operation. All the coroutine builders can be used in a similar fashion, but they will return according to their own signature. For example, fun asyncDo() = async {...} will return a Deferred<T>, and runBlocking {...} will return T.

This function can be called from anywhere in your code without needing to be wrapped, like this:

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

This simplifies the code if the function is called in many places, and it also reduces the flexibility of the function since it will forcefully be executed in a background thread.

It also has the disadvantage that the readability of the code will depend on the correct naming of the function. For example, if you name this implementation loadNews(), the caller of the function may not be aware that this will run asynchronously, and they may not wait for it to complete, which could lead to race conditions or other concurrency issues.

This approach relies on the correct naming of the functions. Incorrect naming will easily cause bugs for the people using the function, since they may not realize that they should suspend their code until the call completes.
主站蜘蛛池模板: 青河县| 辽阳县| 济宁市| 漾濞| 绥宁县| 张家口市| 雷州市| 清河县| 丁青县| 南皮县| 凉城县| 五华县| 罗城| 姜堰市| 辉县市| 聂拉木县| 安泽县| 吴川市| 灵台县| 喀什市| 二连浩特市| 犍为县| 大埔区| 延庆县| 渭南市| 甘谷县| 丰原市| 岢岚县| 潍坊市| 滁州市| 益阳市| 丹巴县| 毕节市| 马尔康县| 礼泉县| 汝南县| 盘山县| 龙川县| 田东县| 定陶县| 台州市|