当前位置:网站首页>Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
2022-06-30 09:01:00 【Byte station】
1. summary
The pending function is Kotlin One of the most important characteristics of a collaborative process , All other concepts are based on it . So we need to understand how it works .
Suspending a coroutine means stopping it in the middle . It's like playing a game , When we want to pause the game , Can be archived first , When you want to continue playing , You can restore the game from the archive . When the process is suspended , It will return one Continuation. It's like archiving in a game , Coroutines can be used Continuation Recover from a hang .
Please note that , This is very different from threads , Thread cannot save , Can only block . The synergy is much more powerful , When suspended , It does not consume any resources of the thread it is on . The process does not have to be resumed on the thread that started the process , You can switch to different threads .
2. recovery
Let's see how it actually works . We use a coprocessor ( Such as runBlocking or launch) Start the coroutines .suspend A function is a function that can suspend a coroutine . It means , They must be in the process ( Or another pending function ) On the call .
This is a simple procedure , Will print “Before” and “After”. If we call the... Provided by the coroutine standard library in the middle suspendCoroutine What happens to the function ?
If you execute the above code , You will find that you will not print “After”, also main The function does not exit . Assist in “Before” Then pause . Our program stopped , Never recovered . So how do we do it ? We can use Continuation To restore the program ?
Let's observe suspendCoroutine call , Notice it with lambda expression ( { }) ending . The function passed as a parameter will be called before pausing . This function will Continuation As a parameter .
Observe the print log , We found that “After” Still not printed . We can use Continuation Of resume Method to resume the execution of the collaboration .
Please note that , In the example above “After” Be printed out , Because we are suspendCoroutine Call in resume function .
from Kotlin 1.3 Start , Continuation The definition of .resumeWith Function instead of resume and resumeWithException function . What we use resume and resumeWithException Is an extension function in the standard library .
We can also use it to start a different thread , The thread will sleep for a period of time before resuming :
We can also extract the code that starts the thread into a function .
This mechanism is effective , But we can also use thread pools instead of threads .
Pausing for a while seems to be a useful feature . Let's extract it into a function . We will name it delay.
That's exactly what it is. Kotlin Process library delay Method has been implemented . The current implementation is complex , Mainly to support testing , But the essential idea is the same .
3. Recovery with value
What you may need to pay attention to is why we will Unit Pass to resume function , Why will we Unit As suspendCoroutine Function generic type .Unit yes suspendCoroutine The return type of the function , It's also Continuation Generic types of .
When we call suspendCoroutine when , We can specify Continuation The return type in .resume The function needs to call the same type .
Hanging is very meaningful to the collaboration process . When we do time-consuming operations , We need to be suspended . for example , When we need from API When getting the network response , If there is no corollary , This thread needs to wait . Because threads are expensive , It would be a huge waste . Especially when this is an important thread , such as Android Main thread on . Use the process , It just hangs the process , Then the thread can do something else . Once the data arrives , The thread will resume from the coroutine hang point .
for instance , We simulate the network to request user information :
Directly in main Call in method suspendCoroutine Not very convenient . We can extract it into a method .
at present , Many popular libraries such as Retrofit or Room Has supported suspend function . That's why we rarely need to be in suspend Reason for using callback function in function . And one and suspendCoroutine Similar approach suspendCancellableCoroutine, I recommend the latter , The latter supports the cancellation function .
You might want to know if API What happens if we return an exception instead of giving us data . What happens if the service crashes or responds incorrectly ?. under these circumstances , We can't return data , Instead, you should throw an exception from the place where the collaboration is suspended
4. Abnormal recovery
Every function we call may return a value or throw an exception . about suspendCoroutine So it is with . We can call resumeWithException Return from the exception . It can be used try catch Capture exception .
5. Suspend a collaboration , Not a function
One thing that needs to be emphasized is that we just suspended a process , Not a function . Imagine , We will Continuation Stored in a variable , And try to recover it after the function call .
It doesn't make any sense .resume Never be called .
Welcome to your attention " Byte station " WeChat official account .
边栏推荐
- How to format an UTC date to use the Z (Zulu) zone designator in php?
- PHP API to obtain QR code and combine to generate pictures
- Mmdet line by line deltaxywhbboxcoder
- File upload component on success event, add custom parameters
- codeforces每日5题(均1700)-第三天
- Unsupportedclassversionerror is reported when starting jar package. How to repair it
- Rew acoustic test (I): microphone calibration
- Alcohol tester scheme: what principle does the alcohol tester measure alcohol solubility based on?
- Mmcv expanding CUDA operator beginner level chapter
- Esp32 things (VIII): music playing function of function development
猜你喜欢
Redis design and Implementation (V) | sentinel sentry
Rew acoustic test (VI): signal and measurement
Using appbarlayout to realize secondary ceiling function
Redis design and Implementation (VI) | cluster (sharding)
Detailed explanation of pipline of mmdetection
Build a docker image of Henkel database from 0
Wechat development tool (applet)
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
Bind threads to run on a specific CPU logical kernel
[kotlin collaboration process] complete the advanced kotlin collaboration process
随机推荐
C # get the current timestamp
基于Svelte3.x桌面端UI组件库Svelte UI
快应用中实现自定义抽屉组件
Based on svelte3 X desktop UI component library svelte UI
CUDA realizes L2 European distance
[untitled]
Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"
Coredata acquisition in swift sorting, ascending, descending
How to format an UTC date to use the Z (Zulu) zone designator in php?
Interference source current spectrum test of current probe
Installation, use and explanation of vulnerability scanning tool OpenVAS
Duplicate entry '2' for key 'primary appears in JPA‘
Esp32 (4): overview of the overall code architecture
Understanding society at the age of 14 - reading notes on "happiness at work"
Influencing factors of echo cancellation for smart speakers
Detailed explanation of pytoch's scatter function
Pytorch BERT
[data analysis and display]
How can we get a satisfactory salary? These routines still need to be mastered
Use Huawei performance management service to configure the sampling rate on demand