- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 231字
- 2021-08-05 10:46:47
CoroutineDispatcher
It's important to understand that in Kotlin, while you can create threads and thread pools easily, you don't access or control them directly. What you do is create a CoroutineDispatcher, which is basically an orchestrator that distributes coroutines among threads based on availability, load, and configuration.
In our current case, for example, we will create a CoroutineDispatcher that has only one thread, so all the coroutines that we attach to it will be running in that specific thread. To do so, we create a ThreadPoolDispatcher – which extends CoroutineDispatcher – with only one thread.
Let's open the MainActivity.kt file that was generated previously – it's in the main package of the app, co.starcarr.rssreader – and update it so that it creates such a dispatcher on the class level:
class MainActivity : AppCompatActivity() {
val netDispatcher = newSingleThreadContext(name = "ServiceCall")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
- Vue 3移動Web開發與性能調優實戰
- Java語言程序設計
- Dynamics 365 for Finance and Operations Development Cookbook(Fourth Edition)
- Oracle WebLogic Server 12c:First Look
- Arduino by Example
- 區塊鏈:以太坊DApp開發實戰
- Mastering Rust
- Mastering KnockoutJS
- Oracle JDeveloper 11gR2 Cookbook
- 青少年學Python(第1冊)
- C語言程序設計
- HTML+CSS+JavaScript網頁設計從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Deep Learning for Natural Language Processing
- Node.js 6.x Blueprints
- 安卓工程師教你玩轉Android