Skip to content

Commit 5566402

Browse files
committed
[test] Add getOrAwaitValue function in LiveDataTestUtil
1 parent f6c9321 commit 5566402

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.chaeny.busoda.stopdetail.util
2+
3+
import androidx.lifecycle.LiveData
4+
import androidx.lifecycle.Observer
5+
import java.util.concurrent.CountDownLatch
6+
import java.util.concurrent.TimeUnit
7+
import java.util.concurrent.TimeoutException
8+
9+
fun <T> LiveData<T>.getOrAwaitValue(
10+
time: Long = 2,
11+
timeUnit: TimeUnit = TimeUnit.SECONDS,
12+
afterObserve: () -> Unit = {}
13+
): T {
14+
var data: T? = null
15+
val latch = CountDownLatch(1)
16+
val observer = object : Observer<T> {
17+
override fun onChanged(value: T) {
18+
data = value
19+
latch.countDown()
20+
this@getOrAwaitValue.removeObserver(this)
21+
}
22+
}
23+
this.observeForever(observer)
24+
25+
afterObserve.invoke()
26+
27+
if (!latch.await(time, timeUnit)) {
28+
this.removeObserver(observer)
29+
throw TimeoutException("LiveData value was never set.")
30+
}
31+
32+
@Suppress("UNCHECKED_CAST") return data as T
33+
}

0 commit comments

Comments
 (0)