Reputation: 1
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
}
Upvotes: 0
Views: 514
Reputation: 23179
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
}
Upvotes: 1