Skip to content

Instantly share code, notes, and snippets.

@marcelpinto
Created April 30, 2018 09:20
Show Gist options
  • Save marcelpinto/9ca9d244d09eb81d1919f503b03615b8 to your computer and use it in GitHub Desktop.
Save marcelpinto/9ca9d244d09eb81d1919f503b03615b8 to your computer and use it in GitHub Desktop.
WeatherExample that shows the getObservation method
sealed class ApiResponse<out T, out S> {
data class Success<out T>(val result: T) : ApiResponse<T, Any>()
data class Failure<out T, out S>(val code: Int, val errorBody: S? = null) : ApiResponse<T, S>()
data class Exception<out T, out S>(val throwable: Throwable) : ApiResponse<T, S>()
}
suspend fun getObservation(lat: Double, lng: Double): ApiResponse<WeatherObservation, Any> {
return withContext(context) {
try {
val response = weatherApi.getObservations("observation", lat, lng, true).execute()
if (response.isSuccessful && response.body() != null) {
ApiResponse.Success(response.body()!!)
} else {
ApiResponse.Failure<WeatherObservation, Any>(response.code(), response.errorBody())
}
} catch (e: Exception) {
ApiResponse.Exception<WeatherObservation, Any>(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment