Skip to content

Instantly share code, notes, and snippets.

@shakil807g
Created January 31, 2018 10:22
Show Gist options
  • Save shakil807g/961f5c63c6501c87c6a9d40fc5e6a1c9 to your computer and use it in GitHub Desktop.
Save shakil807g/961f5c63c6501c87c6a9d40fc5e6a1c9 to your computer and use it in GitHub Desktop.
inline fun <T> tryOrDefault(default: T? = null, block: () -> T?) = try {
block()
} catch(e: Exception){
default
}
inline fun <T> tryOrNull(block: () -> T?) = try {
block()
} catch(e: Exception){
null
}
class ApiLiveData<T> : MutableLiveData<Resource<T>>()
fun <T> ApiLiveData<T>.load(func: () -> Deferred<Wrapper<T>>): LiveData<Resource<T>> {
launch(UI) {
try {
value = Resource.loading()
val response = func().await()
if(response.status != null && response.status!!){
value = Resource.success(tryOrNull { response.body }, tryOrNull { response.message } ?: "" )
}else{
value = Resource.error(response.message ?: "Some thing went wrong!!")
}
}catch (e: HttpException){
e.printStackTrace()
value = Resource.error(tryOrNull { e.response().raw().request().url().toString() }?: "Service Error")
}
catch (e: Throwable){
e.printStackTrace()
value = Resource.error(e.message?: "Network Error")
}
}
return this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment