当前位置:网站首页>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
}
}
边栏推荐
- Network security OpenVAS
- [fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
- 【Camera专题】Camera dtsi 完全解析
- Function definition and call, this, strict mode, higher-order function, closure, recursion
- Certaines fonctionnalités du développement d'applets
- CFdiv2-Fixed Point Guessing-(区间答案二分)
- 微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
- Comment le chef de file gère - t - il l'équipe en cas d'épidémie? Contributions communautaires
- Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
- 函数的定义和调用、this、严格模式、高阶函数、闭包、递归
猜你喜欢
The testing process that software testers should know
stm32F407-------IIC通讯协议
詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信
[Appendix 6 Application of reflection] Application of reflection: dynamic agent
stm32F407-------DMA
MySQL learning 03
全链路数字化转型下,零售企业如何打开第二增长曲线
PyTorch 卷积网络正则化 DropBlock
The technology boss is ready, and the topic of position C is up to you
详细些介绍如何通过MQTT协议和华为云物联网进行通信
随机推荐
Swift development learning
Stm32f407 ------- IIC communication protocol
stm32F407-------ADC
A 30-year-old software tester, who has been unemployed for 4 months, is confused and doesn't know what to do?
Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol
Explore the conversion between PX pixels and Pt pounds, mm and MM
Anna: Beibei, can you draw?
[camera topic] how to save OTP data in user-defined nodes
Machine learning notes (constantly updating...)
Network security - DNS spoofing and phishing websites
leetcode961. Find the elements repeated N times in the array with length 2n
Ni visa fails after LabVIEW installs the third-party visa software
【Camera专题】手把手撸一份驱动 到 点亮Camera
Redis:Redis的简单使用
[fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)
PyTorch 卷积网络正则化 DropBlock
Cfdiv2 Fixed Point Guessing - (2 points for Interval answer)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance o
iptables 4层转发
疫情當頭,作為Leader如何進行團隊的管理?| 社區征文