问题
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?
回答1:
Kotlin coroutines are designed along the "sequential by default" guideline. That means that your API should always expose suspend fun
s 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.
来源:https://stackoverflow.com/questions/60448590/should-a-library-function-be-suspend-or-return-deferred