当前位置:网站首页>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
}
}
边栏推荐
- How to refresh the opening amount of Oracle ERP
- When the epidemic comes, how to manage the team as a leader| Community essay solicitation
- 技术大佬准备就绪,话题C位由你决定
- Custom components, using NPM packages, global data sharing, subcontracting
- 小程序开发的部分功能
- Groovy, "try with resources" construction alternative
- Asian Games countdown! AI target detection helps host the Asian Games!
- LabVIEW安装第三方VISA软件后NI VISA失效
- elastic stack
- [shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)
猜你喜欢
![[shutter] pull the navigation bar sideways (drawer component | pageview component)](/img/6f/dfc9dae5f890125d0cebdb2a0f4638.gif)
[shutter] pull the navigation bar sideways (drawer component | pageview component)

Rockchip3399 start auto load driver
![[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)](/img/66/0fda43da0d36fc0c9277ca86ece252.jpg)
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)

Trial setup and use of idea GoLand development tool

微服务组件Sentinel (Hystrix)详细分析

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

Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol

Redis: simple use of redis

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

elastic stack
随机推荐
可視化yolov5格式數據集(labelme json文件)
DDL basic operation
Cfdiv2 Fixed Point Guessing - (2 points for Interval answer)
Network security - vulnerabilities and Trojans
Socket编程
小程序开发的部分功能
Use go language to realize try{}catch{}finally
stm32F407-------DMA
PS remove watermark details
机器学习流程与方法
我的创作纪念日
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
可视化yolov5格式数据集(labelme json文件)
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
疫情当头,作为Leader如何进行团队的管理?| 社区征文
Analyzing several common string library functions in C language
2022 spring "golden three silver four" job hopping prerequisites: Software Test interview questions (with answers)
LabVIEW安装第三方VISA软件后NI VISA失效
Swift development learning
[Yu Yue education] reference materials of chemical experiment safety knowledge of University of science and technology of China