Last active
January 11, 2020 01:25
-
-
Save watabee/69c813eb581cc95df6f43af725e6f5a6 to your computer and use it in GitHub Desktop.
Extension functions for LiveData
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
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.liveData | |
import androidx.lifecycle.map | |
import androidx.lifecycle.switchMap | |
import kotlinx.coroutines.delay | |
// Combine latest values | |
inline fun <X, Y, Z> LiveData<X>.combineLatest(data: LiveData<Y>, crossinline mapFunction: (X, Y) -> Z): LiveData<Z> { | |
return switchMap { x: X -> data.map { y: Y -> mapFunction(x, y) } } | |
} | |
// Only emit a value from LiveData if a particular timespan has passed without it emitting another value | |
fun <X> LiveData<X>.debounce(timeoutMillis: Long): LiveData<X> { | |
return switchMap { value -> | |
liveData { | |
delay(timeoutMillis) | |
emit(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment