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

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.
主站蜘蛛池模板: 黄骅市| 涿鹿县| 长沙县| 南皮县| 临澧县| 繁昌县| 甘孜| 贵南县| 虞城县| 蓝田县| 镇赉县| 定西市| 金乡县| 新和县| 奈曼旗| 中山市| 永福县| 房产| 龙山县| 高雄县| 南平市| 无棣县| 仙居县| 漳平市| 新巴尔虎左旗| 襄城县| 孟州市| 六枝特区| 灵台县| 延边| 平利县| 寿阳县| 彭阳县| 新野县| 藁城市| 宜君县| 岳西县| 广灵县| 中牟县| 延庆县| 滕州市|