Created
April 20, 2020 06:55
-
-
Save akueisara/1d711fc03e129ac320ecb13fda48cc03 to your computer and use it in GitHub Desktop.
Unit-testing LiveData and other common observability problems: https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04
This file contains hidden or 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
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 | |
// version 1 | |
@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 | |
} | |
// version 2 | |
/* Copyright 2019 Google LLC. | |
SPDX-License-Identifier: Apache-2.0 */ | |
fun <T> LiveData<T>.getOrAwaitValue( | |
time: Long = 2, | |
timeUnit: TimeUnit = TimeUnit.SECONDS | |
): 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) | |
// Don't wait indefinitely if the LiveData is not set. | |
if (!latch.await(time, timeUnit)) { | |
throw TimeoutException("LiveData value was never set.") | |
} | |
@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