Created
January 31, 2018 10:22
-
-
Save shakil807g/961f5c63c6501c87c6a9d40fc5e6a1c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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