getOrAwaitValue

fun <T> LiveData<T>.getOrAwaitValue(time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS): T

Observes a LiveData value until it receives a new value, returning that new value when it gets one unless the timeout is reached.

It is good practice to always use this function in tests to check for the values of all LiveData objects that are meant to have a value. LiveData objects do not emit a value unless they are being observed and this function ensures that there is always an observer when it is called. This is particularly important for LiveData objects which are a transformation of another as the transformation is only executed when there is an observer.

Since the observer is only added as part of this function call, the developer should consider the placement of this function carefully when writing a test so that this call does not miss an earlier value as this can lead to flaky tests.