Skip to content

Instantly share code, notes, and snippets.

@watabee
Last active January 11, 2020 01:25
Show Gist options
  • Save watabee/69c813eb581cc95df6f43af725e6f5a6 to your computer and use it in GitHub Desktop.
Save watabee/69c813eb581cc95df6f43af725e6f5a6 to your computer and use it in GitHub Desktop.
Extension functions for LiveData
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