当前位置:网站首页>Deep understanding of kotlin collaboration context coroutinecontext
Deep understanding of kotlin collaboration context coroutinecontext
2022-06-30 09:01:00 【Byte station】
1. Preface
If you are right about CoroutineContext Don't understand , This article is worth reading carefully , If you can't read it over and over again , You might as well read it several times . The process of writing this article is also my understanding of CoroutineContext The process of deepening understanding .CoroutineContext Is the basis of the collaborative process , It's worth learning
Android Developer pair Context No stranger . stay Android In the system ,Context It can be said that it has great powers , It can get application resources , You can get system resources , You can start Activity.Context There are several well-known subclasses ,Activity、Application、Service, They are very important components in the application .
There is a similar concept in the collaborative process ,CoroutineContext. It is the context in the collaborative process , Through it, we can control which thread the coprocessor executes , You can set the name of the collaboration , It can be used to catch exceptions thrown by the coroutine, etc .
We know , adopt CoroutineScope.launch Method can start a coroutine . The type of the first parameter of this method is CoroutineContext. The default value is EmptyCoroutineContext Singleton object .
At the beginning of the explanation CoroutineContext Before that, let's take a look at the code that we often encounter in a collaborative process 
When I first started learning the collaborative process , We often talk to each other Dispatchers.Main、Job、CoroutineName、CoroutineExceptionHandler Dealing with , They are all CoroutineContext Subclasses of . It's also easy for us to understand them alone ,Dispatchers.Main It refers to distributing the cooperation process to the main thread for execution ,Job Can manage the life cycle of the collaborative process ,CoroutineName You can set the name of the collaboration ,CoroutineExceptionHandler It can catch the exceptions of the cooperation process . however + Operators for most Java Developers even Kotlin Developers will feel fresh and difficult to understand , In association CoroutineContext+ What does it mean ?
Actually + Operator is to put two CoroutineContext Merge into a linked list , I'll explain it in detail later
2. CoroutineContext Class diagram list

According to the class diagram structure, we can divide it into four levels :
- CoroutineContext The parent interface of all context sensitive classes in the collaboration .
- CombinedContext、Element、EmptyCoroutineContext. They are CoroutineContext The direct subclass of .
- AbstractCoroutineContextElement、Job. These two are Element The direct subclass of .
- CoroutineName、CoroutineExceptionHandler、CoroutineDispatcher
( contain Dispatchers.Main and Dispatchers.Default). They are AbstractCoroutineContextElement The direct subclass of .
At the red box in the figure ,CombinedContext Defined size() and contains() Method , This is much like a collection operation ,CombinedContext yes CoroutineContext A collection of objects , and Element and EmptyCoroutineContext But these methods are not defined , The only coroutine context that really implements the set operation is CombinedContext, I'll explain it in detail later
3. CoroutineContext Interface
CoroutineContext Source code is as follows :
First Let's look at the official notes , I summarize its function as :
Persistent context for the coroutine. It is an indexed set of [Element] instances. An indexed set is a mix between a set and a map. Every element in this set has a unique [Key].
- CoroutineContext It's the context of the coroutine .
- CoroutineContext yes element Of set aggregate , There are no duplicate types element object .
- Each of the sets element There's only one Key,Key Can be used to retrieve elements .
I believe most people see this explanation , Will be confused , Since it is set Why not use type directly HashSet To preserve Element.CoroutineContext What is the realization principle of ? The reason is that considering the co process nesting , Use a linked list to achieve better .
next Let's look at several methods defined by the interface 
4. Key Interface

Key Is an interface defined in CoroutineContext One of the interfaces in , As an interface, it does not declare any methods , So it doesn't really have any useful meaning , It's just used to retrieve . So let's see , How to use... In the collaboration library Key Interface .
By observing the examples in the official library of collaborative process , We found that Element Subclasses of must override Key This attribute , and Key The generic type of must be the same as the class name . With CoroutineName For example ,Key Is a companion , meanwhile Key Generic types of are also CoroutineName.
For ease of understanding , I modeled MyElement class , as follows :

by force of contrast kt Class and decompiled java Class we see Key It's just a static variable , And its implementation class , nothing . Its function and HashMap Medium Key similar :
- Realization key-value function , Provide retrieval function for insertion and deletion
- Key yes static Static variables , Globally unique , by Element Provide uniqueness guarantee
Kotlin Grammatical sugar
coroutineContext.get(CoroutineName.Key)
coroutineContext.get(CoroutineName)
coroutineContext[CoroutineName]
coroutineContext[CoroutineName.Key]
Writing is equivalent
4. CoroutineContext.get Method
Source code ( Put it together , The same below )
Usage mode 
Explain
adopt Key retrieval Element. The return value can only be Element perhaps null, Element values in linked list nodes .
- Element get Method : as long as Key With the current Element Of Key Match up , Return to the Element Otherwise return to null.
- CombinedContext get Method : Traversing the linked list , Query and Key equal Element, If we don't find a way back null.
5. CoroutineContext.plus Method
Source code 
Usage mode 
Explain
Put two CoroutineContext Combine into one CoroutineContext, If two are of the same type Element Will return a new Element. If it's two different types Element Will return a CombinedContext. If there are many different types of Element Will return a message CombinedContext Linked list .
I summarize the above algorithm into 5 Kinds of scenes , But in introducing this 5 Before the first scene , Let's start with CombinedContext Data structure of .
6. CombinedContext analysis

because CombinedContext yes CoroutineContext Subclasses of ,left It's also CoroutineContext Type of , So its data structure is linked list . We often use next To represent the next node of the linked list . So why is it called left Well ? I even suspect that the code was written by a left-handed person . The real reason is , A coroutine can start a subprocess , The sub cooperative process can start the sun cooperative process . The parent process is on the left , The subprocess is on the right

Nested start process 
The more the outer layer of the process Context The more on the left , The sketch is as follows ( This is not true , More complicated than that )
The two knowledge points of the linked list are reflected here .CoroutineContext.plus The head insertion method is used in the method .CombinedContext Of toString The method is to print the linked list in reverse order .
7. Five kinds plus scene
according to plus Source code , I have summed up five scenarios that will be covered .
- plus EmptyCoroutineContext
- plus Of the same type Element
- plus The caller of the method does not Dispatcher dependent Element
- plus The only caller of the method is Dispatcher dependent Element
- plus The caller of the method contains Dispatcher relevant Element The linked list of
give the result as follows :
Dispatchers.Main + EmptyCoroutineContextresult :Dispatchers.Main.CoroutineName("c1") + CoroutineName("c2")result :CoroutineName("c2"). Replace the same type directly .CoroutineName("c1") + Job()result :CoroutineName("c1") <- Job. Head insertion is plus Of (Job) Put it at the head of the linked listDispatchers.Main + Job()result :Job <- Dispatchers.Main. Although it's head insertion , however ContinuationInterceptor Must be at the head of the linked list .Dispatchers.Main + Job() + CoroutineName("c5")result :Job <- CoroutineName("c5") <- Dispatchers.Main.Dispatchers.Main At the head of the linked list , Others use head insertion .
If you don't think about Dispatchers.Main The situation of . We can
+use<-Instead of .CoroutineName("c1") + Job()Equivalent toCoroutineName("c1") <- Job
8. CoroutineContext Of minusKey Method
Source code 
Explain
- Element minusKey Method : If Key With the current element Of Key equal , return EmptyCoroutineContext, Otherwise, it is equivalent to no less success , Returns the current element
- CombinedContext minusKey Method : Delete the qualified nodes in the linked list , There are three situations .
Take the following linked list as an example
Job <- CoroutineName(“c5”) <-Dispatchers.Main
No nodes found :minusKey(MyElement). stay Job Go to the node newLeft === left Branch , And so on , stay CoroutineName Take the same branch , stay Dispatchers.Main Take the same branch .
The node is at the end :minusKey(Job). stay CoroutineName(“c5”) Node walking newLeft === EmptyCoroutineContext Branch , Recurse to the head accordingly
The node is not at the tail :minusKey(CoroutineName). stay Dispatchers.Main Go to the node else Branch
9. summary
Study CoroutineContext First of all, we should make clear the inheritance relationship between various types , secondly ,CombinedContext Each specific Element Set , Its data structure is linked list , If readers are familiar with the operation of adding, deleting, modifying and querying linked lists , Then it's easy to understand CoroutineContext principle , Otherwise you want to understand CoroutineContext It's like a blind man touching an elephant .
Remember to pay attention to “ Byte station ” The official account ~
边栏推荐
- Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
- TiDB 6.0:让 TSO 更高效丨TiDB Book Rush
- mysql基础入门 day4 动力节点[老杜]课堂笔记
- [untitled]
- 证券开户的优惠怎样才能得到?在线开户安全?
- 将线程绑定在某个具体的CPU逻辑内核上运行
- Esp32 things (V): analysis of common API of esp32 of Swiss Army knife
- [data analysis and display]
- CUDA realizes L2 European distance
- Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
猜你喜欢

Use Huawei performance management service to configure the sampling rate on demand

Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu

Enhance the add / delete operation of for loop & iterator delete collection elements

Evaluation standard for audio signal quality of intelligent speakers

Anchorgenerator for mmdet line by line interpretation

Rew acoustic test (III): generate test signal

QT connection to Shentong database

Based on svelte3 X desktop UI component library svelte UI

Codeworks 5 questions per day (1700 for each) - the third day

Rew acoustic test (II): offline test
随机推荐
Qt通过Url下载文件
关于Lombok的@Data注解
Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)
Deploy the cow like customer network project on the ECS
el-input 限制只能输数字
How can we get a satisfactory salary? These routines still need to be mastered
Qt连接神通数据库
证券开户的优惠怎样才能得到?在线开户安全?
Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
C # listbox how to get the selected content (search many invalid articles)
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
【付费推广】常见问题合集,推荐榜单FAQ
codeforces每日5题(均1700)-第三天
Is it safe to open an account? How can anyone say that it is not reliable.
Detailed explanation of pytoch's scatter function
How can I get the discount for opening a securities account? Is online account opening safe?
icon资源
Rew acoustic test (IV): test principle of rew
Installation, use and explanation of vulnerability scanning tool OpenVAS
Pytorch BERT