在带有kotlin和suspend函数的coroutine中返回



IN行return@withContextcachedCategories,因为它不能只是返回cachedCateCategories。什么是@withContext?

代码已满:

@辛格尔顿class 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()
this@FoodMenuRemoteSource.cachedCategories = cachedCategories
}
return@withContext cachedCategories
}

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()
this@FoodMenuRemoteSource.cachedCategories = cachedCategories
}
cachedCategories
}

相关内容

  • 没有找到相关文章

最新更新