Skip to content

Instantly share code, notes, and snippets.

@markchristopherng
Created September 18, 2018 06:56
Show Gist options
  • Save markchristopherng/35b329b134acac5d9ad6af53256d4a1c to your computer and use it in GitHub Desktop.
Save markchristopherng/35b329b134acac5d9ad6af53256d4a1c to your computer and use it in GitHub Desktop.
class StateLiveData<T> : MutableLiveData<T>() {
val state = EventLiveData<State>()
init {
clearState()
}
fun post(observable: Observable<T>, successOnFirstValue: Boolean = true): Disposable {
postLoading()
return observable.subscribeOn(Schedulers.io())
.subscribe({
if (successOnFirstValue) {
postValueAndSuccess(it)
} else {
postValue(it)
}
}, { postError(it) }, { postSuccess() })
}
private fun postValueAndSuccess(value: T) {
super.postValue(value)
postSuccess()
}
fun clearState() {
state.postValue(State.Idle)
}
fun postLoading() {
state.postValue(State.Loading())
}
fun postSuccess() {
state.postValue(State.Success())
}
fun postError(throwable: Throwable) {
state.postValue(State.Error(throwable))
}
fun postState(s: State) {
state.postValue(s)
}
/**
* state of this live data, can be extended
*/
open class State {
object Idle : State()
open class Loading : State()
open class Success : State()
open class Error(val error: Throwable) : State()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment