Fer B.
Fer B.

Reputation: 443

In which cases you don't want or you shouldn't use coroutines in Kotlin?

I'd read a lot of the many adventages of using coroutines, but I find nothing about why you shouldn't or couldn't use them.

Why not use all methods as suspend methods, by the way?

I'm having some trouble to understand some concepts here, so with my question I pretend to make the opposite case (why not use it), so I can understand better by contrast.

Upvotes: 7

Views: 1694

Answers (2)

SVK
SVK

Reputation: 756

Please see my answers inline to your questions:

  1. but I find nothing about why you shouldn't or couldn't use them.
    Answer: a. You should not use them for any foreground task.
    b. You should not use them for any simple/real quick operations.
    c. You should not use them for any kind of initialization.

  2. Why not use all methods as suspend methods, by the way?
    Answer:
    a) This will be treated as code smell. Bad practice to do so.
    b) If you mark all functions as suspend, then whenever you want to call a suspend function you will have to create a Coroutine Scope to run it.
    c) Testing of suspend function is difficult. It needs some additional setup of RunBlockingTest from AndroidX.

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200206

The main reason not to have all functions suspendable is the overhead they introduce, at least on the JVM. Every suspendable function compiles into a Java method that receives another parameter, the continuation object, and its body compiles into pretty complex state machine code that, among other things, always instantiates another continuation object and daisy-chains it to the one received as the parameter.

So, whenever you have nothing to gain from coroutines, you shouldn't use them as the default way to do things.

Upvotes: 2

Related Questions