当前位置:网站首页>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
}
}
边栏推荐
- stm32F407-------ADC
- Analyzing several common string library functions in C language
- Hard core observation 547 large neural network may be beginning to become aware?
- Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
- MySQL learning 03
- Leetcode(540)——有序数组中的单一元素
- Network security - man in the middle attack
- [camera topic] how to save OTP data in user-defined nodes
- The Sandbox阐释对元宇宙平台的愿景
- How to refresh the opening amount of Oracle ERP
猜你喜欢

Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux

MySQL学习03

Trial setup and use of idea GoLand development tool
![[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)](/img/e7/915404743d6639ac359bb4e7f7fbb7.jpg)
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)

可视化yolov5格式数据集(labelme json文件)

Niuniu's ball guessing game (dynamic planning + prefix influence)
![[camera topic] complete analysis of camera dtsi](/img/cb/d42589fcf0610600c9dc8c7992d4d7.png)
[camera topic] complete analysis of camera dtsi

PS remove watermark details

Certaines fonctionnalités du développement d'applets

查询商品案例-页面渲染数据
随机推荐
CFdiv2-Fixed Point Guessing-(区间答案二分)
詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信
Query product cases - page rendering data
2022 financial product revenue ranking
[fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
elastic stack
深度(穿透)选择器 ::v-deep/deep/及 > > >
Trial setup and use of idea GoLand development tool
我的创作纪念日
微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
详细些介绍如何通过MQTT协议和华为云物联网进行通信
How to refresh the opening amount of Oracle ERP
机器学习流程与方法
leetcode961. Find the elements repeated N times in the array with length 2n
es6 filter() 数组过滤方法总结
stm32F407-------ADC
What are the key points often asked in the redis interview
机器学习笔记(持续更新中。。。)
全链路数字化转型下,零售企业如何打开第二增长曲线