Created
February 25, 2021 05:22
-
-
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.
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
@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