当前位置:网站首页>Talk about how the kotlin process started?
Talk about how the kotlin process started?
2022-06-30 09:01:00 【Byte station】
1. Preface
This paper mainly introduces the starting principle of synergetic process , If you don't have actual experience in cooperative process or Debug Source code of cooperative process , It may seem like a bit of a struggle , But if you have the opportunity to learn the source code of the collaborative process in the future , Then this article may be of some help to you . This article mainly explains the process of starting the collaboration process , For simplicity , Other important collaborative process knowledge points involved in this process may only be briefly mentioned , This article will not go into details , They will be written separately in the future when they are free .
2. A simple example
First Let's take a simple example , Open a coroutine in the main thread , Print “Hello Coroutines”. Use this simple example to explain how the collaboration process is started .
next We will startCoroutines Method is decompiled into Java file 
We see Kotlin In code Lambda The expression becomes Java Medium Function2 object , And its corresponding concrete class is SuspendLambda.
We notice that it implements three methods :
- Object invokeSuspend(Object var1)
- Continuation create(Object value,Continuation completion)
- Object invoke(Object var1,Object var2)



If you look carefully, you will find ,invokeSuspend and create Method defined in BaseContinuationImpl in ,invoke Method definition Function2 in . and SuspendLambda Inherited ContinuationImpl At the same time, it realized SuspendFunction Interface .
stay Kotlin in , Methods are also objects , The class corresponding to the method of a parameter is Function1, By analogy, the two parameter methods correspond to Function2.
Writing at this point , There are a lot of new things ,suspend、Continuation、CoroutineScope、CoroutineContext, But this article will not cover , Next, let's look at the process of starting the collaboration .
3. The boot process
3.1 CoroutineScope.launch

The function of this method is as follows :
- Create a new... For the new collaboration CoroutineContext
- this paper Case establish StandaloneCoroutine
- call coroutine.start Method to start the process

The function of this method is as follows :
- call initParentJob Method , With the father Job Establishing correlation , When calling cancel Method or sub Job When there is abnormal , Cancellation or exception events can be propagated upward ( This article ignores , It's good to have a simple understanding )
- call start(block, receiver, this), This method is super confusing , What it really calls is CoroutineStart Of invoke Method .
3.2 CoroutineStart.invoke

In this case DEFAULT Branch
3.3 (suspend->T).startCoroutineCancellable

And finally through suspend Methodical startCoroutineCancellable Method to start the process , This article corresponds to lambda, As we mentioned earlier, it corresponds to SuspendLambda
{
println("Hello Coroutines")
}
This method contains several important method calls :
- (suspend R.()->T).createCoroutineUnintercepted
- Continuation.intercepted()
- Continuation.resumeCancellableWith
3.4 (suspend R.() -> T).createCoroutineUnintercepted

Current this Is the closure of the startup process , Previously, we decompile startCoroutines Method , It is found that closures implement create Method , What is called here is generated after decompilation create Method

Parameters completion The corresponding is the co process StandaloneCoroutine, Generated here Function2 Object is also SuspendLambda object
3.5 Continuation.intercepted()

The main function of this method is to generate DispatchedContinuation. It consists of CoroutineDispatcher and Continuation Two parts .Dispatcher Decided to Continuation In which thread , This article is on the main thread
3.6 Continuation.resumeCancellableWith

3.7 MainScope

Dispatchers.Main In the end by the kotlinx.coroutines.android.AndroidDispatcherFactory establish
3.8 AndroidDispatcherFactory

Finally through Handler.post Method to DispatchedContinuation Put into the main thread message queue
3.9 DispatchedTask.run
Android Main thread scheduling , Will eventually be called to DispatchedTask.run In the method , adopt continuation.resume Method to execute the coroutine body .
3.10 BaseContinuationImpl.resumeWith
ContinuationImpl.kt
This method loops through Continuation Of invokeSuspend Method , Until now completion Is that the coroutine itself will jump out of the loop .
Actually print “Hello Coroutines”
3.11 AbstractCoroutine.resumeWith
The coordination process is completed 
Indicates that the execution of the collaboration process ends , It may need to wait for the subprocess to end , After that, you need to inform the parent collaboration process
4. summary
There are too many pre knowledge points in the coordination process , An article cannot explain clearly , Questions can be raised in the comment area . This article mainly explains Dispatchers.Main The process of starting a collaboration .Dispatchers.Default The process of starting the process is completely different from it .
Remember to pay attention to “ Byte station ” The official account ~
边栏推荐
- PHP API to obtain QR code and combine to generate pictures
- asdsadadsad
- 技术管理进阶——管理者如何进行梯队设计及建设
- How to format an UTC date to use the Z (Zulu) zone designator in php?
- [kotlin collaboration process] complete the advanced kotlin collaboration process
- Redis design and Implementation (IV) | master-slave replication
- Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)
- Interpretation of orientedrcnn papers
- Sort (simple description)
- Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
猜你喜欢

Detectron2 source code reading 4-- registrar construction model

How can we get a satisfactory salary? These routines still need to be mastered

Advanced technology management -- how managers design and build echelons

Opencv learning notes-day6-7 (scroll bar operation demonstration is used to adjust image brightness and contrast, and createtrackbar() creates a scroll bar function)

Does the oscilloscope probe affect the measurement of capacitive load?

asdsadadsad

Raspberry pie 4B no screen installation system and networking using VNC wireless projection function

Based on svelte3 X desktop UI component library svelte UI

Installation, use and explanation of vulnerability scanning tool OpenVAS

Opencv learning notes -day4 image pixel reading and writing operations (array traversal and pointer traversal implementation, uchar vec3b data type and mat class functions mat:: at(), mat:: ptr())
随机推荐
Introduction to MySQL basics day4 power node [Lao Du] class notes
Rew acoustic test (II): offline test
Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)
Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
Esp32 things (VIII): music playing function of function development
Deploy the cow like customer network project on the ECS
2021-05-06
Understanding of MVVM and MVC
Influencing factors of echo cancellation for smart speakers
Esp32 things (x): other functions
启动jar包报错UnsupportedClassVersionError,如何修复
快应用中实现自定义抽屉组件
Evaluation standard for audio signal quality of intelligent speakers
Rew acoustic test (VI): signal and measurement
证券开户的优惠怎样才能得到?在线开户安全?
[untitled]
Opencv learning notes-day6-7 (scroll bar operation demonstration is used to adjust image brightness and contrast, and createtrackbar() creates a scroll bar function)
自制GIF动态图-gifcam
Pytorch BERT
Raspberry pie 4B no screen installation system and networking using VNC wireless projection function