Canato
Canato

Reputation: 3978

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

Upvotes: 0

Views: 660

Answers (3)

daneejela
daneejela

Reputation: 14243

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 (i.e. marked with suspend)

So, sometimes you end up calling suspend function inside another suspend function.

Upvotes: 1

Rafa
Rafa

Reputation: 3349

The suspend keyword is just an indicator that a function can be blocking. 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.

Upvotes: 1

Alexey Soshin
Alexey Soshin

Reputation: 17731

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.

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.

Upvotes: 1

Related Questions