库函数应暂停还是应推迟返回 [英] Should a library function be suspend or return deferred

查看:77
本文介绍了库函数应暂停还是应推迟返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我正在编写一个返回字符串的库,这是一个复杂且长期运行的任务.

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
}

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

这两个选项是否都具有(不利)优势,它们是哪些?我应该选择哪一个?

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

推荐答案

kotlin协程是根据默认顺序" 准则.这意味着您的API应该始终公开suspend fun,如果用户确实需要,则可以轻松地将它们包装在async中.

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.

其优点类似于流相对于 hot 流的优点:可悬浮函数仅在控件处于内部时才处于活动状态.当它返回时,它没有留下在后台运行的任务.

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.

每当您返回Deferred时,用户必须开始担心如果他们不等待结果的话会发生什么.某些代码路径可能会忽略它,调用代码可能会获得异常,然后它们的应用程序就会泄漏.

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.

这篇关于库函数应暂停还是应推迟返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆