当前位置:网站首页>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 .
边栏推荐
- Enhance the add / delete operation of for loop & iterator delete collection elements
- 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
- mysql基础入门 day4 动力节点[老杜]课堂笔记
- [data analysis and display]
- Design specification for smart speakers v1.0
- CUDA implements matrix replication
- Talk about writing
- Tidb 6.0: making Tso more efficient tidb Book rush
- Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
- Esp32 things (VIII): music playing function of function development
猜你喜欢

将线程绑定在某个具体的CPU逻辑内核上运行

Axure make menu bar effect

Bind threads to run on a specific CPU logical kernel

Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)

Interpretation of orientedrcnn papers

Self made GIF dynamic graph -gifcam

100 lines of code and a voice conversation assistant

Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)

Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"

Detectron2 source code reading 4-- registrar construction model
随机推荐
Detectron2 source code reading 3-- encapsulating dataset with mapper
Based on svelte3 X desktop UI component library svelte UI
Interference source current spectrum test of current probe
C # get the current timestamp
Rew acoustic test (VI): signal and measurement
Interpretation of source code demand:a rotation equivariant detector for aerial object detection
vite项目require语法兼容问题解决require is not defined
TiDB 6.0:让 TSO 更高效丨TiDB Book Rush
Bottomsheetbehavior principle of realizing the home page effect of Gaode map
Redis design and Implementation (III) | interaction between server and client (event IO model)
[untitled]
Anchorgenerator for mmdet line by line interpretation
证券开户的优惠怎样才能得到?在线开户安全?
[untitled]
启动jar包报错UnsupportedClassVersionError,如何修复
Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
Coredata acquisition in swift sorting, ascending, descending
VIM from dislike to dependence (21) -- cross file search
CUDA realizes L2 European distance