Skip to content

Instantly share code, notes, and snippets.

@Boken
Forked from ch4vi/LiveDataPromise.kt
Created October 11, 2018 11:42
Show Gist options
  • Save Boken/55814f98cbe71895687f13583880baef to your computer and use it in GitHub Desktop.
Save Boken/55814f98cbe71895687f13583880baef to your computer and use it in GitHub Desktop.
Concatenate LiveData
fun <T, R> LiveData<T>.then(callback: (T) -> LiveData<R>): LiveData<R> {
return Transformations.switchMap(this, {
result(it)
})
}
/**
* @param owner is needed to observe the final response and call the view
*/
fun promise(owner: LifecycleOwner) {
func1().then {
Log.d("PROMISE", "first $it")
func2()
}.then {
Log.d("PROMISE", "second $it")
func1()
}.observe(owner, Observer {
Log.d("PROMISE", "observe $it")
})
}
/**
* Example functions representing networking requests or disk read threads
*/
fun func1(): LiveData<String> {
val result = MutableLiveData<String>()
Handler().postDelayed({
result.postValue("foo")
}, 2000)
return result
}
fun func2(): LiveData<String> {
val result = MutableLiveData<String>()
Handler().postDelayed({
result.postValue("bar")
}, 2000)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment