Skip to content

Instantly share code, notes, and snippets.

@AdamSHurwitz AdamSHurwitz/TestUtils.kt
Last active Dec 26, 2019

Embed
What would you like to do?
UDF + Unit Tests - Test Utils
fun ContentViewModel.feedViewState() = this.feedViewState.getOrAwaitValue()
fun ContentViewModel.viewEffects() = this.viewEffect.getOrAwaitValue()
fun <T> LiveData<Event<T>>.observe() = this.getOrAwaitValue().peekEvent()
/**
* Gets the value of a [LiveData] or waits for it to have one, with a timeout.
*
* Use this extension from host-side (JVM) tests. It's recommended to use it alongside
* `InstantTaskExecutorRule` or a similar mechanism to execute tasks synchronously.
*/
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 5,
timeUnit: TimeUnit = TimeUnit.SECONDS,
afterObserve: () -> Unit = {}
): T {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(o: T?) {
data = o
latch.countDown()
this@getOrAwaitValue.removeObserver(this)
}
}
this.observeForever(observer)
afterObserve.invoke()
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
this.removeObserver(observer)
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
You can’t perform that action at this time.