Created
September 18, 2018 06:56
-
-
Save markchristopherng/35b329b134acac5d9ad6af53256d4a1c 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
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