使用 kotlin 和挂起函数在协程中返回
在行 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不允许在 lambda 中使用非本地返回。这就是为什么 @withContext 是必要的。您会看到,那里的代码块实际上不是
getFoodCategories
的主体,而是作为withContext
的第二个参数的 lambda 函数。此外,lambda 中的最后一个表达式也自动成为它的返回值,因此您实际上可以像这样完全保留return@withContext
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 ofwithContext
. Also, the last expression in a lambda is automatically also the return value of it, so you can actually leave thereturn@withContext
out completely like this