当前位置:网站首页>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 .
边栏推荐
- 14岁懂社会-《关于“工作的幸福”这件事儿》读书笔记
- Introduction to MySQL basics day4 power node [Lao Du] class notes
- Introduction to MySQL foundation power node [Lao Du] class assignment
- [untitled]
- Mmdet line by line code interpretation of positive and negative sample sampler
- 快应用中实现自定义抽屉组件
- Detailed explanation of pytoch's scatter function
- QT connection to Shentong database
- Raspberry pie 4B no screen installation system and networking using VNC wireless projection function
- Flink Exception -- No ExecutorFactory found to execute the application
猜你喜欢

Redis design and Implementation (IV) | master-slave replication

Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which

Based on svelte3 X desktop UI component library svelte UI

Flink SQL 自定义 Connector

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 -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)

Detectron2 source code reading 3-- encapsulating dataset with mapper

Duplicate entry '2' for key 'primary appears in JPA‘

vim 从嫌弃到依赖(21)——跨文件搜索

Abstract factory pattern
随机推荐
Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
Circuit analysis of current probe
Opencv learning notes-day5 (arithmetic operation of image pixels, add() addition function, subtract() subtraction function, divide() division function, multiply() multiplication function
Explanation on the use of password profiteering cracking tool Hydra
Axure make menu bar effect
[data analysis and display]
[untitled]
Source code interpretation of detectron2 1--engine
[kotlin collaboration process] complete the advanced kotlin collaboration process
PHP API to obtain QR code and combine to generate pictures
Redis design and Implementation (III) | interaction between server and client (event IO model)
Opencv learning notes -day1 (image reading display imread, imshow, namedwindow)
文件上传 upload 组件 on-success 事件,添加自定义参数
Understanding society at the age of 14 - reading notes on "happiness at work"
Icon resources
127.0.0.1、0.0.0.0和localhost
Installation, use and explanation of vulnerability scanning tool OpenVAS
启动jar包报错UnsupportedClassVersionError,如何修复
Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)
Interviewer: do you understand the principle of recyclerview layout animation?