简体   繁体   English

挂起函数内的挂起函数

[英]Suspend functions inside suspend functions

In some samples/explanations the developer call suspend methods inside suspend methods.在某些示例/说明中,开发人员在挂起方法中调用挂起方法。 Why?为什么?

I know that you cannot call a suspend method outside a launch or another suspend method, but why do it suspend inside suspend?我知道你不能在启动或其他挂起方法之外调用挂起方法,但为什么它在挂起内挂起? Memory issues?内存问题? More threads would manager better the memory?更多的线程会管理更好的内存吗?

Thanks in advance for any input提前感谢您的任何意见

The question and statements are a bit backwards, it seems. 问题和陈述似乎有些倒退。 Let's try to sort this out. 让我们尝试解决这个问题。

You want to mark your method as suspendable if it blocks. 如果方法阻塞,您想将其标记为可挂起。 It's a directive to Kotlin compiler to rewrite everything that comes after method marked with suspend as a continuation. 这是Kotlin编译器的指令,用于重写标有suspend作为继续的方法之后的所有内容。

This enables in turn better concurrency. 这又可以实现更好的并发性。 While your method blocks, continuation is suspended, and same thread works on other tasks. 当您的方法阻塞时,继续将被挂起,并且同一线程可以执行其他任务。

Marking your method as suspend doesn't affect memory footprint or amount of threads Kotlin runtime uses. 将您的方法标记为suspend不会影响内存占用或Kotlin运行时使用的线程数量。

The suspend keyword is just an indicator that a function can be blocking. suspend关键字只是一个函数可以被阻塞的指示。 It doesn't inherently do anything besides make sure the compiler knows that it can only be called at the root with a coroutine. 除了确保编译器知道只能在协程的根调用它之外,它本质上不会做任何事情。

Meaning that a chain of suspend functions has to be started with a launch , async etc. 这意味着必须通过launchasync等启动一系列暂停功能。

When you write a suspend function you don't know all the places where you could use it, just like you don't know that with the regular functions.当您编写挂起函数时,您并不知道可以使用它的所有地方,就像您不知道常规函数一样。 You just know that it takes time to execute and because of that needs to be called within coroutine (ie marked with suspend)您只知道执行需要时间,因此需要在协程中调用(即标记为挂起)

So, sometimes you end up calling suspend function inside another suspend function.因此,有时您最终会在另一个挂起函数中调用挂起函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM