Skip to content

Instantly share code, notes, and snippets.

@prokash-sarkar
Created February 25, 2021 05:22
Show Gist options
  • Save prokash-sarkar/15aa4b6454b59b316e82c112d3a15253 to your computer and use it in GitHub Desktop.
Save prokash-sarkar/15aa4b6454b59b316e82c112d3a15253 to your computer and use it in GitHub Desktop.
If you need to observe LiveData changes, then you can use an extension function called LiveDataTestUtil. It will help you observe LiveData changes without any extra effort.
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 2,
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()
[email protected](this)
}
}
this.observeForever(observer)
try {
afterObserve.invoke()
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
throw TimeoutException("LiveData value was never set.")
}
} finally {
this.removeObserver(observer)
}
@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