return in coroutine with kotlin and suspend functions

499 Views Asked by At

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
}
1

There are 1 best solutions below

0
On

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
}