-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5c24ecf
commit 3cb6a86
Showing
5 changed files
with
184 additions
and
9 deletions.
There are no files selected for viewing
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
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
42 changes: 42 additions & 0 deletions
42
app/src/test/java/com/fatherofapps/androidbase/LiveDataTestUtil.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package com.fatherofapps.androidbase | ||
|
||
import androidx.annotation.VisibleForTesting | ||
import androidx.lifecycle.LiveData | ||
import androidx.lifecycle.Observer | ||
import java.util.concurrent.CountDownLatch | ||
import java.util.concurrent.TimeUnit | ||
import java.util.concurrent.TimeoutException | ||
|
||
|
||
@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() | ||
this@getOrAwaitValue.removeObserver(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 | ||
} |
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
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