使用 kotlin 和挂起函数在协程中返回

发布于 2025-01-10 10:40:25 字数 794 浏览 0 评论 0原文

在行 return@withContext cachedCategories 中,因为它不能仅返回 cachedCategories。什么是@withContext?

完整代码:

@Singleton 类 FoodMenuRemoteSource @Inject 构造函数(private val foodMenuApi: FoodMenuApi) {

private var cachedCategories: List<FoodItem>? = null

suspend fun getFoodCategories(): List<FoodItem> = withContext(Dispatchers.IO) {
    var cachedCategories = cachedCategories
    if (cachedCategories == null) {
        cachedCategories = foodMenuApi.getFoodCategories().mapCategoriesToItems()
        [email protected] = cachedCategories
    }
    return@withContext cachedCategories
}

IN line return@withContext cachedCategories because it can't just be return cachedCategories only. Whats @withContext ?

Code full:

@Singleton
class FoodMenuRemoteSource @Inject constructor(private val foodMenuApi: FoodMenuApi) {

private var cachedCategories: List<FoodItem>? = null

suspend fun getFoodCategories(): List<FoodItem> = withContext(Dispatchers.IO) {
    var cachedCategories = cachedCategories
    if (cachedCategories == null) {
        cachedCategories = foodMenuApi.getFoodCategories().mapCategoriesToItems()
        [email protected] = cachedCategories
    }
    return@withContext cachedCategories
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-01-17 10:40:25

不允许在 lambda 中使用非本地返回。这就是为什么 @withContext 是必要的。您会看到,那里的代码块实际上不是 getFoodCategories 的主体,而是作为 withContext 的第二个参数的 lambda 函数。此外,lambda 中的最后一个表达式也自动成为它的返回值,因此您实际上可以像这样完全保留 return@withContext

private var cachedCategories: List<FoodItem>? = null

suspend fun getFoodCategories(): List<FoodItem> = withContext(Dispatchers.IO) {
    var cachedCategories = cachedCategories
    if (cachedCategories == null) {
        cachedCategories = foodMenuApi.getFoodCategories().mapCategoriesToItems()
        [email protected] = cachedCategories
    }
    cachedCategories
}

You are not allowed to have a non-local return in a lambda. That's why @withContext is necessary. You see, the code block there is in fact not the body of the getFoodCategories but the lambda function that is the second argument of withContext. Also, the last expression in a lambda is automatically also the return value of it, so you can actually leave the return@withContext out completely like this

private var cachedCategories: List<FoodItem>? = null

suspend fun getFoodCategories(): List<FoodItem> = withContext(Dispatchers.IO) {
    var cachedCategories = cachedCategories
    if (cachedCategories == null) {
        cachedCategories = foodMenuApi.getFoodCategories().mapCategoriesToItems()
        [email protected] = cachedCategories
    }
    cachedCategories
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文