Skip to content

Instantly share code, notes, and snippets.

@ahmedrizwan
Last active August 25, 2019 02:23
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 ahmedrizwan/365bc7f52b7941d5f14930fe5b0a3315 to your computer and use it in GitHub Desktop.
Save ahmedrizwan/365bc7f52b7941d5f14930fe5b0a3315 to your computer and use it in GitHub Desktop.
class ActionStateLiveData<T>(
private val coroutineContext: CoroutineContext,
fetchData: (suspend () -> Response<T>)
) {
private val action = MutableLiveData<Action>()
private var data: T? = null // backing data
val state = action.switchMap {
liveData(context = coroutineContext) {
when (action.value) {
Action.Load -> {
emit(UIState.Loading)
}
Action.SwipeRefresh -> {
emit(UIState.SwipeRefreshing)
}
Action.Retry -> {
emit(UIState.Retrying)
}
}
try {
val response = fetchData()
val body = response.body()
when {
response.isSuccessful && body != null -> {
data = body
emit(UIState.Success(body))
}
action.value == Action.SwipeRefresh -> {
emit(UIState.SwipeRefreshFailure(Exception()))
}
else -> {
emit(UIState.Failure(Exception()))
}
}
} catch (exception: Exception) {
when {
action.value == Action.SwipeRefresh -> {
emit(UIState.SwipeRefreshFailure(Exception()))
data?.let {
// emit success with existing data
emit(UIState.Success(it))
}
}
else -> {
emit(UIState.Failure(Exception()))
}
}
}
}
}
// Helpers for triggering different actions
fun retry() {
action.value = Action.Retry
}
fun swipeRefresh() {
action.value = Action.SwipeRefresh
}
fun load() {
action.value = Action.Load
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment