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

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)
}
}
In this and many other cases throughout the book, modifiers such as private, protected, open, and others may not be written in the examples as a way to reduce the code – thus improving the formatting for the book. Please take into account that the best practice is to always make each member as inaccessible as possible. Also, in many cases the correct modifier will be found in the code files that come with the book, since there's no formatting constraint there.
主站蜘蛛池模板: 色达县| 罗山县| 青田县| 赣州市| 南平市| 扶沟县| 西藏| 桐柏县| 公主岭市| 洛宁县| 阿城市| 青龙| 南丹县| 霍林郭勒市| 左云县| 甘泉县| 阿巴嘎旗| 达日县| 嵊泗县| 驻马店市| 和林格尔县| 景德镇市| 罗田县| 于田县| 乐陵市| 文山县| 承德市| 汽车| 尤溪县| 德江县| 佛坪县| 梨树县| 鄄城县| 乐至县| 修文县| 资阳市| 嵊泗县| 大宁县| 汤阴县| 搜索| 宜君县|