Skip to content

Instantly share code, notes, and snippets.

@ahmedeltaher
Created December 14, 2021 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedeltaher/752cc885d07203cb1211e3b3c9d258bd to your computer and use it in GitHub Desktop.
Save ahmedeltaher/752cc885d07203cb1211e3b3c9d258bd to your computer and use it in GitHub Desktop.
package com.task.data.remote
import com.task.data.Resource
import com.task.data.dto.recipes.Recipes
import com.task.data.dto.recipes.RecipesItem
import com.task.data.error.NETWORK_ERROR
import com.task.data.error.NO_INTERNET_CONNECTION
import com.task.data.remote.service.RecipesService
import com.task.utils.NetworkConnectivity
import retrofit2.Response
import java.io.IOException
import javax.inject.Inject
/**
* Created by AhmedEltaher
*/
class RemoteData @Inject
constructor(
private val serviceGenerator: ServiceGenerator,
private val networkConnectivity: NetworkConnectivity
) : RemoteDataSource {
override suspend fun requestRecipes(): Resource<Recipes> {
val response = processCall(object : API {
override suspend fun call(): Any {
return serviceGenerator.createService(RecipesService::class.java)
}
})
return when (response) {
is List<*> -> {
Resource.Success(data = Recipes(response as ArrayList<RecipesItem>))
}
else -> {
Resource.DataError(errorCode = response as Int)
}
}
}
private suspend fun processCall(api: API): Any? {
if (!networkConnectivity.isConnected()) {
return NO_INTERNET_CONNECTION
}
return try {
val response: Response<*> = api.call() as Response<*>
val responseCode = response.code()
if (response.isSuccessful) {
response.body()
} else {
responseCode
}
} catch (e: IOException) {
NETWORK_ERROR
}
}
internal interface API {
suspend fun call(): Any
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment