当前位置:网站首页>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
}
}
边栏推荐
- 2022 spring "golden three silver four" job hopping prerequisites: Software Test interview questions (with answers)
- Stm32f407 ------- IIC communication protocol
- Storage basic operation
- What are MySQL locks and classifications
- In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
- Processing of tree structure data
- Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
- 我的创作纪念日
- 【Camera专题】HAL层-addChannel和startChannel简析
- Technology sharing | Frida's powerful ability to realize hook functions
猜你喜欢

PyTorch 卷积网络正则化 DropBlock

Use go language to realize try{}catch{}finally

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

Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem

easyPOI

Stm32f407 ------- IIC communication protocol

【Camera专题】手把手撸一份驱动 到 点亮Camera

Rockchip3399 start auto load driver

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

Recommendation letter of "listing situation" -- courage is the most valuable
随机推荐
[camera special topic] Hal layer - brief analysis of addchannel and startchannel
去除网页滚动条方法以及内外边距
Hard core observation 547 large neural network may be beginning to become aware?
Use go language to realize try{}catch{}finally
Problems encountered in small program development of dark horse shopping mall
easyPOI
Iptables layer 4 forwarding
Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt
When the epidemic comes, how to manage the team as a leader| Community essay solicitation
The testing process that software testers should know
[Yu Yue education] reference materials of love psychology of China University of mining and technology
How can retail enterprises open the second growth curve under the full link digital transformation
Network security - Information Collection
詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信
[leetcode] 797 and 1189 (basis of graph theory)
Network security OpenVAS
【Camera专题】手把手撸一份驱动 到 点亮Camera
Network security NAT network address translation
String replace space
ByteDance data Lake integration practice based on Hudi