Skip to content

Instantly share code, notes, and snippets.

@ch4vi
Last active February 1, 2019 08:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ch4vi/0f7893bd830f195a99881a30b3cb7640 to your computer and use it in GitHub Desktop.
Save ch4vi/0f7893bd830f195a99881a30b3cb7640 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
}
@AkshayChordiya
Copy link

Looks promising

@darwind
Copy link

darwind commented Jul 4, 2018

What's result(it) here? I know what it is, but I can't figure where you get result from?

@ebabel
Copy link

ebabel commented Aug 27, 2018

Looks like result was renamed to callback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment