Should a library function be suspend or return deferred

家住魔仙堡 提交于 2021-02-07 20:29:00

问题


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 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.



来源:https://stackoverflow.com/questions/60448590/should-a-library-function-be-suspend-or-return-deferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!