Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a library function be suspend or return deferred

Let's assume I'm writing a library that returns a string which is a complex and long running task.

I can chose between offering this

interface StringGenerator {
   suspend fun generateString(): String
}

or

interface StringGenerator {
   fun generateString(): Deferred<String>
}

Are there any (dis-)advantages of either of the options and which are they? Which should I choose?

like image 731
fweigl Avatar asked May 15 '26 10:05

fweigl


1 Answers

Kotlin coroutines are designed along the "sequential by default" guideline. That means that your API should always expose suspend funs and the user, if and when they really need it, can easily wrap them in async.

The advantage of that is analogous to the advantages of cold flows with respect to hot flows: a suspendable function is active only while control is inside it. When it returns, it has not left behind a task running in the background.

Whenever you return a Deferred, the user must start worrying what happens if they don't manage to await on the result. Some code paths may ignore it, the calling code may get an exception, and then their application has a leak.

like image 140
Marko Topolnik Avatar answered May 18 '26 14:05

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!