Last active
March 19, 2023 09:24
-
-
Save JoseAlcerreca/35828c25fca123c8a115d6251cf3f45b to your computer and use it in GitHub Desktop.
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
/* 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