当前位置:网站首页>Coroutinecontext in kotlin
Coroutinecontext in kotlin
2022-07-03 02:07:00 【yu-Knight】
List of articles
The context of the coroutine
CoroutineContext Is a set of elements that define the behavior of a coroutine . It consists of the following :
- 1.Job: Control the lifecycle of the process .
- 2.CoroutineDispatcher: Distribute tasks to the appropriate threads .
- 3.CoroutineName: The name of the program , It's useful when debugging .
- 4.CoroutineExceptionHandle: Handling uncapped exceptions .
Combine elements in context
Sometimes we need to define multiple elements in the context of a collaboration . We can use + Operator to implement . for instance , We can specify a scheduler to start the process and specify a name at the same time :
@Test
fun `test CoroutineContext`() = runBlocking<Unit> {
launch(Dispatchers.Default + CoroutineName("test")) {
println("I'm working in thread${
Thread.currentThread().name}")
}
}
Inheritance of coroutine context
- For the newly created collaboration , its CoroutineContext Will include a new Job example , It will help us to control the lifecycle of the coprocessor . And the rest of the elements go from CoroutineContext Inherits from the parent class of , The parent class may be another coroutine or the one that created it CoroutineScope
@Test
fun `test CoroutineContext extend`() = runBlocking<Unit> {
val scope = CoroutineScope(Job() + Dispatchers.IO + CoroutineName("test"))
val job = scope.launch {
// The new program will CoroutineScope As a parent
println("${
coroutineContext[Job]} ${
Thread.currentThread().name}")
val result = async {
// adopt async The new coroutine created will take the current coroutine as a parent
println("${
coroutineContext[Job]} ${
Thread.currentThread().name}")
"OK"
}.await()
}
job.join()
/** "test#2":StandaloneCoroutine{Active}@11443e84 DefaultDispatcher-worker-1 @test#2 "test#3":DeferredCoroutine{Active}@2cf1f044 DefaultDispatcher-worker-3 @test#3 */
}
The context of the coroutine = The default value is + inherited CoroutineContext + Parameters
- Some elements contain default values :Dispatchers.Default By default CoroutineDispatcher, as well as “coroutine” By default CoroutineName;
- inherited CoroutineContext yes CoroutineScope Or his father's CoroutineContext;
- Parameters passed into the collaboration builder take precedence over inherited context parameters , Therefore, the corresponding parameter value will be overridden .
- The ultimate parent CoroutineContext It will contain Dispatchers.IO instead of scope In the object Dispatcher.Main, Because it is overwritten by the parameters in the constructor of the collaboration . Besides , Pay attention to the parent CoroutineContext Inside Job yes scope Object's Job( Red ), And new Job example ( green ) Will be assigned to a new coroutine CoroutineContext.

@Test
fun `test CoroutineContext extend2`() = runBlocking<Unit> {
val coroutineExceptionHandler = CoroutineExceptionHandler {
_, exception ->
println("Caught $exception")
}
val scope = CoroutineScope(Job() + Dispatchers.Main + coroutineExceptionHandler)
// new CoroutioneContext = Parent CoroutineContext + Job()
val job = scope.launch(Dispatchers.IO) {
// New association
}
}
边栏推荐
- 转载收录6.5大侠写的部分Qt开发经验
- Groovy, "try with resources" construction alternative
- 2022 spring "golden three silver four" job hopping prerequisites: Software Test interview questions (with answers)
- Network security ACL access control list
- 小程序开发黑马购物商城中遇到的问题
- stm32F407-------ADC
- Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt
- Rockchip3399 start auto load driver
- 去除网页滚动条方法以及内外边距
- Huakaiyun (Zhiyin) | virtual host: what is a virtual host
猜你喜欢

Depth (penetration) selector:: v-deep/deep/ and > > >

微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題

Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)

Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt

Processing of tree structure data

The testing process that software testers should know
![[camera topic] turn a drive to light up the camera](/img/d3/7aabaa5c75813abc4a43820b4c3706.png)
[camera topic] turn a drive to light up the camera

Ni visa fails after LabVIEW installs the third-party visa software

Performance test | script template sorting, tool sorting and result analysis

Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
随机推荐
小程序开发黑马购物商城中遇到的问题
Basic operation of view
File class (add / delete)
[shutter] bottom navigation bar implementation (bottomnavigationbar bottom navigation bar | bottomnavigationbaritem navigation bar entry | pageview)
Explore the conversion between PX pixels and Pt pounds, mm and MM
Modify table structure
Learn BeanShell before you dare to say you know JMeter
Hard core observation 547 large neural network may be beginning to become aware?
Storage basic operation
Problems encountered in small program development of dark horse shopping mall
[leetcode] 797 and 1189 (basis of graph theory)
Custom components, using NPM packages, global data sharing, subcontracting
详细些介绍如何通过MQTT协议和华为云物联网进行通信
How to deal with cache hot key in redis
【Camera专题】Camera dtsi 完全解析
Network security ACL access control list
Network security - phishing
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
Some functions of applet development
Method of removing webpage scroll bar and inner and outer margins