Last active
August 25, 2019 02:23
-
-
Save ahmedrizwan/365bc7f52b7941d5f14930fe5b0a3315 to your computer and use it in GitHub Desktop.
This file contains 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
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