File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
feature/stopdetail/src/test/java/com/chaeny/busoda/stopdetail/util Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments