Skip to content

Instantly share code, notes, and snippets.

@JoseAlcerreca
Last active March 19, 2023 09:24
Show Gist options
  • Save JoseAlcerreca/35828c25fca123c8a115d6251cf3f45b to your computer and use it in GitHub Desktop.
Save JoseAlcerreca/35828c25fca123c8a115d6251cf3f45b to your computer and use it in GitHub Desktop.
/* Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 2,
timeUnit: TimeUnit = TimeUnit.SECONDS
): T {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(o: T?) {
data = o
latch.countDown()
[email protected](this)
}
}
this.observeForever(observer)
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
throw TimeoutException("LiveData value was never set.")
}
@Suppress("UNCHECKED_CAST")
return data as T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment