- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 312字
- 2021-08-05 10:46:50
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"
}
}
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.
- Building a RESTful Web Service with Spring
- Reactive Programming with Swift
- Protocol-Oriented Programming with Swift
- PHP從入門到精通(第4版)(軟件開發視頻大講堂)
- 響應式架構:消息模式Actor實現與Scala、Akka應用集成
- ArcGIS for Desktop Cookbook
- JSP程序設計實例教程(第2版)
- Oracle Database XE 11gR2 Jump Start Guide
- 數據結構:Python語言描述
- Swift 2 Design Patterns
- Python AI游戲編程入門:基于Pygame和PyTorch
- Mastering Rust
- IBM Cognos 10 Report Studio Cookbook(Second Edition)
- 微信小程序開發零基礎入門
- Node.js Web Development(Third Edition)